Lua C API Examples
This file contains 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
#include <stdio.h> | |
#include <string.h> | |
#include <lua.h> | |
#include <lauxlib.h> | |
#include <lualib.h> | |
// Helper function to print the stack contents | |
// Values other than numbers and strings are printed as "(null)" | |
void print_stack(lua_State *L, char* title){ | |
int nargs = lua_gettop(L); | |
printf(" --- STACK at %s ---\n", title); | |
for(int i=1; i<=nargs; i++) { | |
printf(" - S[%d] = %s\n", i, lua_tostring(L, i)); | |
} | |
printf(" ---\n"); | |
} | |
int l_cls(lua_State *L) { | |
print_stack(L, "entry cls"); | |
lua_settop(L,0); // clear stack | |
lua_pushstring(L, "Not returned"); | |
lua_pushvalue(L, lua_upvalueindex(1)); // ret1 | |
lua_pushvalue(L, lua_upvalueindex(2)); // ret2 | |
lua_pushvalue(L, lua_upvalueindex(3)); // ret3 | |
lua_pushstring(L, "Hello world from CLS!"); // ret4 | |
print_stack(L, "exit cls"); | |
return 4; | |
} | |
int l_closure(lua_State *L) { | |
print_stack(L, "entry l_closure"); | |
lua_pushstring(L, "a"); | |
lua_pushstring(L, "b"); | |
lua_pushstring(L, "c"); | |
lua_pushcclosure(L, l_cls, 3); | |
print_stack(L, "exit l_closure"); | |
return 1; | |
} | |
int l_simple(lua_State *L) { | |
print_stack(L, "entry l_simple"); | |
// push some more garbage onto the stack | |
lua_pushstring(L, "some "); | |
lua_pushstring(L, "more"); | |
lua_pushstring(L, "garbage"); | |
// push some return values | |
lua_pushstring(L, "ret1"); | |
lua_pushstring(L, "ret2"); | |
lua_pushstring(L, "ret3"); | |
// return the top 3 values on the stack | |
// in order S[-3], S[-2], S[-1] | |
print_stack(L, "exit l_simple"); | |
return 3; | |
} | |
int main(int argc, char **argv){ | |
static const struct luaL_Reg l_lib[] = { | |
{"simple", l_simple}, | |
{"closure", l_closure}, | |
{NULL, NULL} | |
}; | |
lua_State *L = lua_open(); | |
luaL_openlibs(L); | |
luaL_openlib(L, "lib", l_lib, 0); | |
luaL_dostring(L, "print(\"Simple function call:\")"); | |
luaL_dostring(L, "print(lib.simple(1,2,3))"); | |
luaL_dostring(L, "print(\"Call a closure\")"); | |
luaL_dostring(L, "print(lib.closure()(1,2,3))"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example run: