#include #include #include // A simple C function to add two numbers int c_add(lua_State *L) { double a = luaL_checknumber(L, 1); double b = luaL_checknumber(L, 2); lua_pushnumber(L, a + b); return 1; // one return value } int c_print(lua_State *L) { const char *c = luaL_checkstring(L, 1); printf("%s\n", c); return 0; } static int luaB_print(lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; for (i = 1; i <= n; i++) { /* for each argument */ size_t l; const char *s = luaL_tolstring(L, i, &l); /* convert it to string */ if (i > 1) /* not the first element? */ lua_writestring("\t", 1); /* add a tab before it */ lua_writestring(s, l); /* print it */ lua_pop(L, 1); /* pop result */ } lua_writeline(); return 0; } static int luaB_type(lua_State *L) { int t = lua_type(L, 1); luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); lua_pushstring(L, lua_typename(L, t)); return 1; } int main(void) { lua_State *L = luaL_newstate(); // luaL_openlibs(L); // Load Lua standard libraries const lua_Number ver = lua_version(NULL); printf("Lua version: %.2f\n", ver); printf("Lua version: %s\n", LUA_VERSION); // Register the C function as a global Lua function lua_register(L, "c_add", c_add); lua_register(L, "myprint", c_print); lua_register(L, "print", luaB_print); lua_register(L, "type", luaB_type); // Run the Lua script if (luaL_dofile(L, "script.lua") != LUA_OK) { fprintf(stderr, "Error: %s\n", lua_tostring(L, -1)); lua_pop(L, 1); // remove error message } lua_close(L); return 0; }