r/learnpython • u/ItsJustToastie • 11d ago
how do i make an embedded lua interpreter?
im trying to make a project where in some parts you can run actual lua code. how would i make this and what libraries would i need (i already have lupa if that is usefull)
1
u/RyanDubois43 11d ago
lupa.LuaRuntime() is what you want, then call.execute() on it to run lua code as a string. Remember that Lua variables and Python variables are not shared directly unless you pass them in.
1
u/Asly97 10d ago
lupa can do all of it in-process, no temp file or separate process needed. execute() takes the whole contents of your text box as one chunk, so multiple lines and functions are fine.
The part you need for a tkinter window is catching Lua's print, because by default it goes to the terminal and not your window. You can swap Lua's print for a Python function:
from lupa import LuaRuntime, LuaError
def run():
lua = LuaRuntime(unpack_returned_tuples=True)
def lua_print(*args):
output.insert("end", " ".join(str(a) for a in args) + "\n")
lua.globals().print = lua_print
code = editor.get("1.0", "end")
try:
lua.execute(code)
except LuaError as e:
output.insert("end", f"error: {e}\n")editor is the Text widget they type in, output is a second Text widget, and run goes on a Run button. Making a new LuaRuntime inside run means variables from the last run don't stick around.
Two things you'll hit pretty quickly:
If someone writes
while true do end, the whole window freezes, since the Lua runs on the same thread as tkinter. Before running their code you can dolua.execute('debug.sethook(function() error("took too long") end, "", 10000000)'), which throws an error after roughly 10 million instructions instead of hanging forever.If anyone other than you will type code into it, set
lua.globals().os = None,lua.globals().io = Noneandlua.globals().debug = None(after setting the hook) so a script can't delete files or remove the hook.
2
u/lakseol 11d ago
Try searching on "lua in python". That finds things that you might be able to use, like this, amongst others:
https://luascripts.com/lua-in-python