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

lua_load and calling functions

Started by Krun Jul 6, 2004 at 11:25 AM 5 replies 4.1k views
Original Post
Krun
Krun
Hi! Me again! I can't figure out why this doesn't work: "If there are no errors, lua_load pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message." - from the Lua manual Now, I get the pushed Lua function with this code: luaL_loadfile(L, path); // load the script lua_CFunction funct = lua_tocfunction(L,lua_gettop(L)); // get the function from the top of the stack But when I call func(L) I get a exception. I wan't to use this code cause it would allow me to execute the script multiple times just by calling the function instead of loading the whole script every time (too slow for game).
trolocsis
trolocsis
you forgot a call to lua_pcall.
Sneftel
Sneftel
Quote:
Original post by Krun

luaL_loadfile(L, path); // load the script
lua_CFunction funct = lua_tocfunction(L,lua_gettop(L)); // get the function from the top of the stack


lua_tocfunction won't return anything but NULL if the function isn't actually a C function (that is, pushed onto the stack with lua_pushcfunction or lua_pushcclosure). And if you loaded it in with luaL_loadfile, it isn't a C function. Methinks you should check out lua_ref and lua_getref for how to retain a reference to a Lua object.
Krun
Krun
This code works fine but only the first time. The second time I try to run it I get a "atempted to call a nil value" error cause Lua seems to pop the code once it is runned.

Is there any way to load a script from a file once, and then run it in memory more than once without having to reload the script file?
Sneftel
Sneftel
Yes. As I said, use lua_ref and lua_getref. They'll allow you to hold a reference to your function from C.
Krun
Krun
Quote:
Original post by Sneftel
use lua_ref and lua_getref.

I belive this could be it, but I'm using Lua 5.0.2 and there is no lua_pushref function (only lua_ref,lua_unref,lua_getref).
Krun
Krun
Just foud this post:
http://archive.neotonic.com/archive/lua-l/messages/14563?mode=author&noheader=1#doc_14563

The guy says that you have to create a table in the registry and load script chunks into it. That way the chunks will allways exsist (won't be destroyed after run). Still, I don't know how to implement the above system (Lua n00b).

Topic Locked

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

Sign in to reply to this topic.