Skip to content

Instantly share code, notes, and snippets.

@MarcoLizza
Last active December 9, 2021 21:44
Show Gist options
  • Save MarcoLizza/7dade79afe6f166ef75a7cd96919fae8 to your computer and use it in GitHub Desktop.
Save MarcoLizza/7dade79afe6f166ef75a7cd96919fae8 to your computer and use it in GitHub Desktop.
Pass a table from C to Lua and let the script modify it.
#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>
#include <stdio.h>
static const char *_script =
"function init(t)\n"
" t['width'] = 320\n"
" t['height'] = 240\n"
"end\n";
int main(int argc, char *argv[])
{
lua_State *L = luaL_newstate();
// Load and evaluate the script.
(void)luaL_dostring(L, _script);
// Create a a table on the stack, and populate with a single key/value pair.
lua_newtable(L); // [] -> [T]
lua_pushstring(L, "width"); // [T] -> [T S]
lua_pushnumber(L, 0.0); // [T S] -> [T S N]
lua_rawset(L, -3); // [T S N] -> [T]
// Get a reference to the global function to be called, a copy the table
// reference to pass it as an argument. Then call the function.
lua_getglobal(L, "init"); // [T] -> [T F]
lua_pushvalue(L, -2); // [T F] -> [T F T]
lua_call(L, 1, 0); // [T F T] -> [T]
// Dump the table content.
lua_pushnil(L); // [T] -> [T N]
while (lua_next(L, -2)) { // [T N] -> [T K V]
printf("t[%s]=%f\n", lua_tostring(L, -2), lua_tonumber(L, -1));
lua_pop(L, 1); // [T K V] -> [T K]
}
// Dispose the table from the stack.
lua_pop(L, 1); // [T] -> []
// So long, and thanks for all the fish...
lua_close(L);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment