Jump to content
  • Advertisement
Sign in to follow this  
NumberXaero

Lua dofile error output as C string?

This topic is 3778 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a lua script file that doesnt run (intentionally). Im running the script in a console app using dofile, what Id like is to be able to get is the error output from the failed compile. The same output that the online lua demo (http://www.lua.org/cgi-bin/demo) generates when a script run fails. Ive got the lua print calls as const char* by registering a function for luas "print", but Im not sure where to look for the compile/run errors that dofile/dostring create?

Share this post


Link to post
Share on other sites
Advertisement
Use loadfile(). It loads and compiles a file and returns the compiled code as a function. If the compilation failed it returns nil and the error string.

You could do something like this:

local result, errorStr = loadfile("somefile.lua")
if result == nil then
-- Compilation failed, print the error message.
print(errorStr)
else
-- Compilation was successful, run the code.
result()
end

Share this post


Link to post
Share on other sites
And here's a C(-ish) version:

int error = luaL_loadfile(state, "file.lua");
if(error) // if non-0, then an error
{
// the top of the stack should be the error string
if (!lua_isstring(state, lua_gettop(state)))
return "no error";

// get the top of the stack as the error and pop it off
string str = lua_tostring(state, lua_gettop(state));
lua_pop(state, 1);

return str;
}
else
{
// if not an error, then the top of the stack will be the function to call to run the file
lua_pcall(state, 0, LUA_MULTRET, 0); // once again, returns non-0 on error, you should probably add a little check
}

Quote:
Lua Docs:

The lua_pcall function returns 0 in case of success or one of the following error codes (defined in lua.h):

* LUA_ERRRUN: a runtime error.
* LUA_ERRMEM: memory allocation error. For such errors, Lua does not call the error handler function.
* LUA_ERRERR: error while running the error handler function.

Loads a Lua chunk. 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. The return values of lua_load are:

* 0: no errors;
* LUA_ERRSYNTAX: syntax error during pre-compilation;
* LUA_ERRMEM: memory allocation error.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!