简体   繁体   English

一个简单的Lua解释器嵌入在wxWidgets中

[英]A simple Lua interpreter embedded in wxWidgets

I am trying to write a simple Lua interpreter using wxWidgets as my GUI. 我正在尝试使用wxWidgets作为我的GUI编写一个简单的Lua解释器。 I am reading the Lua command from a multiline textbox. 我正在从多行文本框中读取Lua命令。 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 如果我尝试评估像3 + 5这样的简单表达式,那么我会收到以下错误

 [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: 如果您希望用户输入表达式(如1+2a+math.sqrt(b) ),则在将其提供给解释器之前必须先添加“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);

However, you probably don't want to prepend it if the user enter a statement (like a=1; b=2 ). 但是,如果用户输入语句(例如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. 请注意,lua_tostring将返回块返回的任何内容。 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) . 如果块没有返回任何内容,则lua_tostring将返回nil,就像任何返回任何内容的函数在调用ret=func(whatever)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM