开发者

Embedded a Lua interactive prompt window in C#

I tried to provide some script features in my C# App. After some searches, The Lua and LuaInterface looks like a reasonable way to do it. By embedding a Lua VM in my C# code, I can load a Lua script and process methods defined in the C# class without any problems.

开发者_JS百科

However, I wonder is there a way to not only execute a lua script file in my c# program, but also to have a lua interactive prompt in my program? Thus I can type commands and see the returns immediately.

Any hint about where I should start to work on it will be very helpful!

Best Regards


Lua's debug module contains a very basic interactive console: debug.debug() (the Lua manual suggests this module should be used only for debugging).

If that doesn't meet your needs, it's easy enough to implement one yourself. If you were to write it in Lua itself, the absolute bare bones console would be:

while true do
   io.write("> ")
   loadstring(io.read())()
end

That'll crash on either a syntax or runtime error. A slightly less minimal version, which captures (and ignores) errors:

while true do
   io.write("> ")
   local line = io.read()
   if not line then break end -- quit on EOF?
   local chunk = loadstring(line)
   if chunk then
      pcall(chunk)
   end
end

This could be enhanced by displaying syntax errors (second return value from loadstring on failure), runtime errors (second return value from pcall on failure), return values from evaluated code ([2..N] return values from pcall on success), etc.

If you want to get really fancy, you can allow people to enter multi-line statements. Look at src/lua.c in the source distro to see how this is done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜