Skip to main content
GameDev.net gamedev.net
🔒 Locked

Lua function call

Started by MetaCipher Oct 13, 2007 at 9:37 AM 4 replies 1k views
Original Post
MetaCipher
MetaCipher
I am attempting to call a function within a Lua script: cpp

    if(luaL_loadfile(Lua_Handle, File) == 0) {
        lua_getglobal(Lua_Handle, "OnLoop");

        if(lua_pcall(Lua_Handle, 0, 1, 0) != 0) {
            printf("Error running function `OnLoop': %s\n", lua_tostring(Lua_Handle, -1));
        }

        if(!lua_isnumber(Lua_Handle, -1)) {
            printf("Returned parameter is invalid\n");
        }

        int Ret = lua_tonumber(Lua_Handle, -1);
        lua_pop(Lua_Handle, 1);
    }else{
        printf("Unable to load Lua file\n");
    }
script

function OnLoop()
	io.write("I am looping!");

	return 1;
end
When I try to call it, it returns: Error running function `OnLoop': attempt to call a nil value Returned parameter is invalid I appreciate any help offered, thanks. [Edited by - MetaCipher on October 15, 2007 12:48:49 PM]
rip-off
rip-off
Have you opened the IO library on your lua_State?
MetaCipher
MetaCipher
I am calling: luaL_openlibs(Lua_Handle);

Which, I've tested it prior (calling the entire script) and it works just fine.

[Edited by - MetaCipher on October 15, 2007 12:07:59 PM]
Merick Zero
Merick Zero
I don't know much about cpp, but I don't think it's the io lib that's causing the problem

try replacing -1 with 1 and see what happens:

if(!lua_isnumber(Lua_Handle, -1)) {

change to:

if(!lua_isnumber(Lua_Handle, 1)) {
MetaCipher
MetaCipher
The if(!lua_isnumber(Lua_Handle, -1)) { isn't causing the problem. The function call itself is failing, so the returned value is going to be invalid.

[Edited by - MetaCipher on October 15, 2007 12:54:50 PM]
MetaCipher
MetaCipher
I figured it out, Lua is trying to access the function before it was added to the global table. So, if I run the script first, and then try to grab the function it works just fine.

[Edited by - MetaCipher on October 15, 2007 12:18:39 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.