1
votes

I spent few hours trying to make it work without success. I have a C++ program with function exposed to Lua script. Lua script uses it like this:

    setData('type', {a=1, b=2, c=3})

So first argument is string and second is table.

My current and best version of C++ setData function looks like this:

    string sType;
    map<string, uint8_t> mOptions;

    int nArgs = lua_gettop(i_pState);
    if (nArgs == 2)
    {
        if (lua_isstring(i_pState, 1) != 0)
            sType = lua_tostring(i_pState, 1);

        if (lua_istable(i_pState, 2) != 0)
        {
            lua_pushnil(i_pState);
            while(lua_next(i_pState, 2))
            {
                uint8_t nValue = uint8_t(lua_tonumber(i_pState, -1));
                string  sKey   = lua_tostring(i_pState, -2);

                mOptions[sKey] = nValue;

                lua_pop(i_pState, 1);
            }
            lua_pop(i_pState, 1);
        }
    }

    return 0;

It works fine but causes "program.exe has triggered a breakpoint" error afterwards at the end when lua_close() function called. What is wrong with this code?

UPD1. I'm not getting error without handling second argument.

UPD2. My code behaves very strangely. I think it could be issue of mixing extern "C" and C++ code.

UPD3. Turns out this is heap corruption. I can't understand where is cause. Probably this is not related to lua at all.

1
I don't know C++, but in C lua_tostring returns const char *. Is it safe to assign a const char * value to string variables (sKey and sType)? - cyclaminist
It must be safe. string class should copy character sequence into internal buffer. - YuriM

1 Answers

0
votes

Finally! Recompilation of Lua code as C++ code didn't work (positive thing is I don't have to worry about extern "C" anymore). But I found two redundant lua_pop() calls. I removed them and now it works fine.

I didn't expect Lua to be so dangerous!