I’m attempting to call a function inside of a lua file called test2.lua
This is the contents of test2.lua:
function abc(path)
t = {}
table.insert(t, "a")
return t
end
As you can see it takes a single input and returns a string.
Here is my C code. It’s pretty simple. However my call getglobal in order to call that function does not work… lua_getglobal says it isn’t a function when I test it… Any reason why this is? Shouldn’t abc be a global function returnable inside of the source file? Why then does it only find nil for this global?
L = lua_open();
luaL_openlibs(L);
luaL_loadfile(L, "src/test2.lua");
lua_getglobal(L, "abc");
lua_pushstring(L, "coollll");
int error = 0;
if ((error = lua_pcall(L, 1, 1, 0)) == 0)
{
std::cout << "cool";
}
EDIT:
calling lua_getglobal is causing my program to break control regardless of using loadfile or dofile… any idea why?
The function
luaL_loadfile()reads, parses, and compiles the named Lua file. It does not execute any of its content. This is important in your case because the statementfunction abc(path)…endhas no visible effect until it is executed. Thefunctionkeyword as you’ve used it is equivalent to writingIn this form, it is clearer that the variable named
abcis not actually assigned a value until the code executes.When
luaL_loadfile()returns, it has pushed an anonymous function on the top of the Lua stack that is the result of compiling your file. You need to call it, andlua_pcall()will do the trick. Replace your reference toluaL_loadfile()with this:At this point, test2.lua has been executed and any functions it defined or other global variables it modified are available.
This is a common enough idiom, that the function
luaL_dofile()is provided to load and call a file by name.There is a second, more subtle issue in your code as presented. The function
abc()uses a variable namedt, but you should be aware thattas used is a global variable. You probably meant to writelocal t = {}at the top ofabc().