user441521
user441521

Reputation: 6988

C++ lua table mapped to lua file

How can I make a lua table in C++ map to a lua script where the script defines the table properties and methods, so the resulting lua file looks something like:

Script.test = 5

function Script:Update()
end

So this script could be read in many times but each time it should get its own unique table in C++.

The idea is that from C++ I want to call each unique Update() method and be able to read/set its test variable.

Let's say you are making a video game and I told you if you make scripts structured like this and attach them to models that the game will run the Update() method every frame and that the variables you define are local to that script/model.

Upvotes: 1

Views: 486

Answers (1)

greatwolf
greatwolf

Reputation: 20838

This answer is just to elaborate on my comment above. One simple idea to achieve what you're describing is to just create that local table right in the script file and return that table at the end.

local Script = {}

Script.test = 5
Script.foo = "bar"

function Script:Update()
end

return Script

This is the usual approach taken to put lua modules into its own namespace and to avoid global scope pollution.

You can grab and use the returned Script table off the stack with something like this:

// load and execute your script
luaL_dofile(L, "script.lua");

// Run Script:Update()
lua_getfield(L, -1, "Update");
lua_pushvalue(L, -2);
lua_call(L, 1, 0);

You can wrap the above code snippet into a function to make it easier to call as many times as desired. You can even make it more efficient by caching the compiled script.lua somewhere to avoid reparsing and recreating the wrapping function everytime this function is called. For example:

lua_getfield(L, LUA_REGISTRYINDEX, "cached_script");
if (lua_isnil(L, -1))
{
  luaL_loadfile(L, "script.lua");
  lua_pushvalue(L, -1);
  lua_setfield(L, LUA_REGISTRYINDEX, "cached_script");
}
lua_pcall(L, 0, 0, 0);
// etc.

Upvotes: 1

Related Questions