I am new to embedding Lua to C++ and currently trying to learn and hone my skills before embedding lua into a bigger project.
Here is my C++ code:
int main()
{
int result=0;
lua_State *L = luaL_newstate();
static const luaL_Reg lualibs[] =
{
{ "base", luaopen_base },
{"math",luaopen_math},
{"table", luaopen_table},
{"io",luaopen_io},
{ NULL, NULL}
};
const luaL_Reg *lib = lualibs;
for(; lib->func != NULL; lib++)
{
lib->func(L);
lua_settop(L, 0);
}
int status=luaL_dofile(L,"example.lua");
if(status == LUA_OK)
{
result = lua_pcall(L, 0, LUA_MULTRET, 0);
}
else
{
std::cout << " Could not load the script." << std::endl;
}
printf("\nDone!\n");
lua_close(L);
return 0;
}
example.lua:
print("Hello from Lua")
print(3+5)
x=math.cos(3.1415)
print(x)
The output is:
Hello from Lua
8
Could not load the script.
Done!
Although I am loading the math library (or I think I am loading) with luaopen_math, it seems that math.cos function is not working.
What might be going on? And can you please explain if there is a simpler way of loading all of the Lua libraries to be able to run a complex Lua script.
What is the difference (performance, size ...) between individually loading libraries and loading with luaL_openlibs. – macroland Feb 08 '14 at 09:08