I am trying to write a simple Lua interpreter using wxWidgets as my GUI. I am reading the Lua command from a multiline textbox. 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 then I get the following error
[string "line"]:1: syntax error near <eof>
Any ideas appreciated.
If you want the user to enter an expression (like 1+2
or a+math.sqrt(b)
), you must prepend "return " to it before giving it to the interpreter:
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);
However, you probably don't want to prepend it if the user enter a statement (like a=1; b=2
). Since you are reading multiline text code you are likely getting string of statements separated by newlines. In this case you should not prepend return; the issue with your test is that you were executing an expression, can't be done. Test with statement(s), several comments show some like the following are all statements
a=4
return 1+2
return math.sqrt(a)
print('hi')
whereas
a
4
1+2
math.sqrt(a)
'hi'
are all expressions. Note that lua_tostring will return whatever the chunk returns. If the chunk doesn't return anything then lua_tostring will return nil, just as any function that returns nothing would do when called as ret=func(whatever)
.