Lua scripting line by line

妖精的绣舞 提交于 2020-01-02 06:42:29

问题


I added Lua scripting to my C# Application by using the DynamicLua libary and it works very well. I would like to implement that you get the current line which is being executed (Like in Visual Studio) and highlight it.

Currently I am doing this:

   public static void RunLua(string LuaToExecute)
    {
        dynamic lua = new DynamicLua.DynamicLua();

        string[] lua_s_split = LuaToExecute.Split('\n');
        int counter = 0;
        foreach (string line in lua_s_split)
        {
            // highlight current line in editor
            HighlightLine(counter + 1);

            //execute current line 
            lua(line);
            counter++;
        }
    }

This is working great with my Lua code like

move(20, 19)
sleep(1000)
move(5, 19)

but I cant only execute one line statements. Like my bound function move(). But I would also like to use multiline statements like functions and loops. If the text editor contains:

function test()
    return  "Hallo Welt"
end

The lua(line) will raise an exception because only the first line function test() is passed and the interpreter is missing the end statement.

What can I do? Should I check if the line begins with an function,while... command and than scan for end blocks and add it to a string so I can execute and highlight this multiline statement all at one? Would this possible? How would I do it?

Please Help.


回答1:


I would like to implement that you get the current line which is being executed (Like in Visual Studio) and highlight it.

Don't do this by feeding Lua the script a line at a time. Run the entire script and let Lua notify you when execution switches to a new line, via a debug hook:

Programming in Lua: Hooks
Lua manual: debug.sethook




回答2:


[EDIT] At the time of this answer, I was unaware of the LUA parser mentioned in the accepted answer. I am agreed with that poster that you should use official parsing libraries wherever possible rather than rolling your own. The below answers the original question, but should not be seen as the ultimate answer. Please view the accepted answer for the correct method to handle this problem.[/EDIT]

You're explicitly calling it to parse the line of code / execute the LUA.

If you have a multiline function, ensure you're passing the full thing before calling the execution block.

var myCommand = new StringBuilder()

... myCommand.Append(line) ...

foreach (string line in lua_s_split)
    {
        // highlight current line in editor
        HighlightLine(counter + 1);

        //execute current line 
        If(NeedsToExecute(istrue))
        {
            lua(myCommand.ToString());
            counter++;
        }
        else{myCommand.appendline(line)
    }


来源:https://stackoverflow.com/questions/24334574/lua-scripting-line-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!