Skip to main content
 首页 » 编程设计

python之在 Lua 中实现外部源代码块

2025年04月02日11pengyingh

我正在寻找编写一个 Lua 脚本并让它也从 Python 源代码执行一些东西,就好像它是这样的:

#!/bin/lua 
 
-- begin lua part 
print "Hello" 
 
-- begin python part 
 
Somehow_Executes_Python { 
print "Hello" #In python, of course 
} 
 
-- End Script 

明白了吗? 我不确定这是否可能,但如果我能以某种方式在受控 block 中实现外部源代码,那就太好了。我已经看到关于从不同的文件/链接/源调用它们的其他事情,但我希望它直接从 lua 源代码内部工作,而不是完全从不同的文件。

请您参考如下方法:

最简单的方法是遵循以下思路:

#!/usr/bin/env lua 
 
local python = function(code) 
  local file = assert(io.popen('python', 'w')) 
  file:write(code) 
  file:close() 
end 
 
-- begin lua part 
print "Hello from Lua" 
 
--begin python part 
 
python [=[ 
print "Hello from Python" 
]=] 
 
-- End Script 

逐行解释(没有代码高亮,SO上的Lua好像坏了):

#!/usr/bin/env lua 
-- The above is a more sure-fire way to run Lua on linux from a shebang 
 
-- This function runs python code as follows 
local python = function(code) 
  -- It opens a write pipe to the python executable 
  local file = assert(io.popen('python', 'w')) 
  -- pipes the code there 
  file:write(code) 
  -- and closes the file 
  file:close() 
  -- This is an equivalent of running 
  -- $ python <code.py 
  -- in the shell. 
end 
 
-- Begin Lua part 
-- I added "from Lua" to better see in the output what works or not. 
print "Hello from Lua" 
 
-- Begin Python part 
-- We're calling our python code running function,  
-- passing Lua long string to it. This is equivalent of 
-- python('print "Hello from Python"') 
python [=[ 
print "Hello from Python" 
]=] 
 
-- End Script 

我想您希望 Lua 和 Python 代码之间至少有一些互操作性。实现起来有点困难,您应该采用何种方式在很大程度上取决于您实际要解决的问题的细节。

最干净的方法可能是创建一种或另一种套接字对,并让 Lua 和 Python 代码来讨论它。

您可以从一个 VM(例如 Lua)到另一个(例如 Python)读取变量或调用函数的解决方案,反之亦然,通常会由于多种原因导致困惑(我尝试了很多并实现了几个我自己)。