I have the following lua code, which runs fine in an online interpreter:
__sprite_properties = {
events = {}
}
function bind_event(event_name, fun)
table.insert(__sprite_properties.events, { event_name, fun })
print(__sprite_properties.events[1][1])
end
foo = function()
return 0
end
bind_event("foo_event", foo)
>> foo_event
But when I try to load and run the script in C++ using sol2 library, I've got the following error at the table.insert
statement:
script.lua:6: attempt to index global 'table' (a nil value)
stack traceback: script.lua:6: in function 'bind_event' -- script.lua:13: in main chunk
I'm using LuaJIT as lua distribution. The code used to load the script in lua is the following snippet:
sol::state lua;
lua.open_libraries(sol::lib::base);
try {
lua.safe_script_file("script.lua");
}
catch (const sol::error& e) {
std::cout << e.what() << std::endl;
}
How comes that this code can't execute properly when loaded in c++?
Have you loaded the standard Lua libraries in your C++ code? You seem to have loaded only the base library, not the table library:
lua.open_libraries(sol::lib::base);