Last active
November 16, 2020 19:54
-
-
Save AntonioND/6578ce0d3405ec569a0fef5ebccd1721 to your computer and use it in GitHub Desktop.
Lua example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # You need to do: | |
| # sudo apt install liblua5.4-dev | |
| gcc -o test test.c `pkg-config --cflags lua54` `pkg-config --libs lua54` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Test | |
| io.write("Calling C hook\n"); | |
| y = 42 | |
| z = c_test(y); | |
| io.write("C wrote: ", z, "\n"); | |
| io.write("Returning 3 back to C\n"); | |
| x = 1 + 2 | |
| return x |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Example of how to load a Lua script with C hooks that take arguments. | |
| #include <lua.h> | |
| #include <lualib.h> | |
| #include <lauxlib.h> | |
| #include <stdlib.h> | |
| #include <stdio.h> | |
| int lua_cfunction_test(lua_State *L) | |
| { | |
| // Number of arguments | |
| int narg = lua_gettop(L); | |
| // Get argument of the function and remove it from the stack | |
| lua_Integer y = lua_tointeger(L, -1); | |
| lua_pop(L, 1); | |
| printf("%s: %d\n", __func__, y); | |
| // Return y + 1 to Lua | |
| lua_pushinteger(L, y + 1); | |
| // Number of results | |
| return 1; | |
| } | |
| int main(void) | |
| { | |
| // Create Lua state | |
| lua_State *L = luaL_newstate(); | |
| // Load Lua libraries | |
| luaL_openlibs(L); | |
| // Load script from file | |
| int status = luaL_loadfile(L, "script.lua"); | |
| if (status) { | |
| // On error, the error message is at the top of the stack | |
| fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1)); | |
| exit(1); | |
| } | |
| // Register C function | |
| lua_register(L,"c_test",lua_cfunction_test); | |
| // Run script with 0 arguments and expect one return value | |
| int result = lua_pcall(L, 0, 1, 0); | |
| if (result) { | |
| fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1)); | |
| exit(1); | |
| } | |
| // Get returned value and remove it from the stack (it's at the top) | |
| int ret = lua_tointeger(L, -1); | |
| lua_pop(L, 1); | |
| printf("Script returned: %d\n", ret); | |
| // Close Lua | |
| lua_close(L); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment