2

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.

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

lucemia
  • 6,349
  • 5
  • 42
  • 75
  • 1
    (more sophisticated shells: [Is there a lua enhanced interactive shell like python with IPython? - Stack Overflow](https://stackoverflow.com/questions/25615456/is-there-a-lua-enhanced-interactive-shell-like-python-with-ipython)) – user202729 Jan 10 '23 at 00:41

1 Answers1

2

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.

Mud
  • 28,277
  • 11
  • 59
  • 92
  • It is a bad idea to use anything from `debug` module not for debugging. I suggest to remove the first paragraph from this answer. – Alexander Gladysh May 01 '11 at 13:21
  • The OP didn't say what he wanted the console for. It may very well *be* for debugging, in which case the information is useful. A disclaimer would be more appropriate than removal. I'll add that now. – Mud May 02 '11 at 01:43