1

I use the following code to call Lua function from C++ but it crashes sometimes.

void callLuaFunction(lua_State *L, const char *name)
{
    if (L == nullptr) return;
    lua_getglobal(L, name);
    if (lua_type(L, -1) != LUA_TFUNCTION)
        return;
    if (lua_pcall(L, 0, 0, 0))
        error("%s", lua_tostring(L, -1));
}

Is there anything wrong with my code?

Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • 2
    I assume you are using SWIG. Have you looked at [my answer](https://stackoverflow.com/a/51152666/1944004) to your other question? – Henri Menke Jul 06 '18 at 06:06
  • Yes, I did. But the problem is I needed to use it in `CPP` file not `i` file since I needed to use the function with `SWIGLUA_FN fn` argument in a C++ Class. But I didn't know how to write the class in `i` file so I decided to just take the function name as `string` instead. But regardless of that, this is a different question I would like to know. – Zack Lee Jul 06 '18 at 06:24
  • @HenriMenke I tried adding `lua_pop(L, 1);` at the end and it doesn't seem to crash no more. Do you think it's related to the problem I'm having? – Zack Lee Jul 06 '18 at 06:28
  • @HenriMenke Please help me Sir. – Zack Lee Jul 06 '18 at 08:11
  • 1
    Well, your code is not showing anything that could crash, so I don't really know how to help, sorry. – Henri Menke Jul 06 '18 at 08:42
  • OKay Thank you Sir. – Zack Lee Jul 06 '18 at 08:45
  • @HenriMenke Please take a look at my question. https://stackoverflow.com/questions/51208011/how-to-access-variables-of-the-class-that-runs-the-lua-script-from-lua – Zack Lee Jul 06 '18 at 10:09

0 Answers0