r/learnpython • u/ItsJustToastie • 5d 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)
3
Upvotes
2
u/lakseol 5d 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
1
u/RyanDubois43 5d 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 4d 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:
editoris the Text widget they type in,outputis 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:
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.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.