🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

lua_load and calling functions

Started by
5 comments, last by Krun 19 years, 12 months ago
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: <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 </code> 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).
Advertisement
you forgot a call to lua_pcall.
Quote: Original post by Krun
<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
</code>

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.
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?
Yes. As I said, use lua_ref and lua_getref. They'll allow you to hold a reference to your function from C.
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).
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).

This topic is closed to new replies.

Advertisement