Skip to main content
gamedev.net
🔒 Locked 🎮 Unity

Lua file loading problems

Started by Silvo Jan 13, 2007 at 9:59 PM 1 replies 1.4k views
Original Post
Silvo
Silvo
Gday! I am trying to load a Lua file and have Lua store it in the registry instead of the stack (or at least that is my understanding of the matter), as discussed here. Here is my source:

int main()
{
	lua_State* lua;
	lua = luaL_newstate();
	luaL_openlibs(lua);

	luaL_loadfile(lua, "co.lua");
	int ref = luaL_ref(lua, LUA_REGISTRYINDEX);

	lua_rawgeti(lua, LUA_REGISTRYINDEX, ref);

	lua_call(lua, 0, 0);
	lua_getglobal(lua, "Init");

	lua_call(lua, 0, 0);

	do {
		lua_rawgeti(lua, LUA_REGISTRYINDEX, ref);
		lua_getglobal(lua, "Update");
		lua_call(lua, 0, 1);
	} while ((int)lua_tonumber(lua, -1) == 0);

	luaL_unref(lua, LUA_REGISTRYINDEX, ref);
	lua_close(lua);
	return 0;
}


It reaches the first lua_call() call, then panics. What am I doing wrong? Oh, the lua source co.lua is:

function Init()
	print "Init"
	co = coroutine.create(Move)
end

function Move()
	print "first"
	coroutine.yield()
	print "second"
	coroutine.yield()
	print "third"
end

function Update()
	coroutine.resume(co)
	
	if coroutine.running(co)
	   return 0
	else
		return 1
	end
end

Zorbfish
Zorbfish
If you had checked the return value of luaL_loadfile you would have noticed that it was returning the LUA_ERRSYNTAX error code and by calling lua_error:

PANIC: unprotected error in call to Lua API (co.lua:18: 'then' expected near 'return')

Also once you've executed your chunk you do not need to keep it (unless you will need to add the code from the script again). You are calling it over and over in a do-while loop. The first time it was called Init, Move, and Update into the global table so you can just reference them directly from then on.
Silvo
Silvo
Thanks a lot!

Works perfectly now!

I was not aware of the chunk issue either, thanks!

Topic Locked

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

Sign in to reply to this topic.