Reputation: 237
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?
lua_getglobal crashing program
Upvotes: 0
Views: 3485
Reputation: 43326
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 statement function abc(path)
...end
has no visible effect until it is executed. The function
keyword as you've used it is equivalent to writing
abc = function(path)
t = {}
table.insert(t, "a")
return t
end
In this form, it is clearer that the variable named abc
is 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, and lua_pcall()
will do the trick. Replace your reference to luaL_loadfile()
with this:
if (luaL_loadfile(L, "src/test2.lua") || lua_pcall(L, 0, LUA_MULTRET, 0)) {
// do something with the error
}
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 named t
, but you should be aware that t
as used is a global variable. You probably meant to write local t = {}
at the top of abc()
.
Upvotes: 8
Reputation: 35449
It's not enough to call luaL_loadfile
: this puts a chunk onto the stack. Either follow up with luaL_[p]call
to execute the chunk (thus making the function available), or use luaL_dofile
.
Upvotes: 3