Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle errors in Lua when executing arbitrary strings?

Tags:

c++11

lua

lua-api

I'm going for absolute minimalism here. (It's been a while since I've worked with the Lua C API.)

#include <lua.hpp>
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv)
{
    lua_State* state = luaL_newstate();
    luaL_openlibs(state);

    string input;

    while (getline(cin, input))
    {
        auto error = luaL_dostring(state, input.c_str());

        if (error)
        {
            cerr << "Lua Error: " << lua_tostring(state, -1) << '\n';
            lua_pop(state, 1);
        }
    }

    lua_close(state);
    return 0;
}

This program works fine as long as I feed it perfect Lua. However, if I enter something bad (such as asdf()), the program crashes! Why is it not handling my error gracefully?

I've tried breaking out the calls before. It crashes on the call to lua_pcall itself. I never make it past that line.

like image 984
TheBuzzSaw Avatar asked Aug 25 '26 19:08

TheBuzzSaw


1 Answers

The binary download (5.2.1 I believe) has a bug that was corrected in 5.2.3. I rebuilt the library from source, and now my program works fine.

like image 126
TheBuzzSaw Avatar answered Aug 28 '26 17:08

TheBuzzSaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!