Simple Lua interpreter built into wxWidgets

I am trying to write a simple Lua interpreter using wxWidgets as my GUI. I am reading the Lua command from a multi-line text field. Here is my code:

    wxString cmdStr = m_OutputWindow->GetLineText(line-1); //Read text

    const char* commandStr=(const char*)cmdStr.mb_str();
    int err=luaL_loadbuffer(luastate,commandStr,strlen(commandStr),"line")||lua_pcall(luastate, 0, 0, 0);
    wxString outputstr;
    if(err)
    {
        outputstr=wxString::FromUTF8(lua_tostring(luastate,-1));
        lua_pop(luastate, 1);
    }

If I try to evaluate a simple expression like 3 + 5, I get the following error

 [string "line"]:1: syntax error near <eof>

Any ideas appreciated.

+3
source share
1 answer

If you want the user to enter an expression (for example, 1+2or a+math.sqrt(b)), before passing it to the interpreter, you must add a "return":

const std::string cmdStr = "return " + m_OutputWindow->GetLineText(line-1).ToStdString();
int err = luaL_loadbuffer(luastate, cmdStr.c_str() , cmdStr.size(), "line") 
       || lua_pcall(luastate, 0, 0, 0);

, , , (, a=1; b=2). , , , , . ; , , . (-) (-), :

a=4
return 1+2
return math.sqrt(a)
print('hi')

a
4
1+2
math.sqrt(a)
'hi'

- . , lua_tostring , . , lua_tostring , , , ret=func(whatever).

+2

All Articles