Lua5.2::为每个脚本创建不同的环境

Lua5.2::为每个脚本创建不同的环境,lua,Lua,这是我遇到的问题的简化版本: [bot0.lua] function OnHit(bot) // Where the bot structure and vec3 // generated using SWIG and registered to a // "global" lua_State that I maintain. bot.color = vec3( 1.0, 0.0, 0.0) end; [bot1.lua] function OnHit(bot) bot.color =

这是我遇到的问题的简化版本:

[bot0.lua]

function OnHit(bot)

// Where the bot structure and vec3 
// generated using SWIG and registered to a 
// "global" lua_State that I maintain.
bot.color = vec3( 1.0, 0.0, 0.0)
end;
[bot1.lua]

function OnHit(bot)

bot.color = vec3( 0.0, 1.0, 0.0)
end;
在加载时,对于每个脚本,我首先执行以下操作(伪代码):

bot->script->L=lua\u newthread()
luaL_加载缓冲区(bot->script->L,botXXX.lua。。。
lua_调用(bot->script->L。。。
然后在运行时从我的程序中,当一个机器人被击中时,我调用:

luaL_dostring( bot->script->L, "OnHit(GetBot(\"<the bot name>\")" );
luaL\u dostring(bot->script->L,“OnHit(GetBot(\“\”)”);
(其中GetBot也是在全局lua_状态中注册的函数)

问题是bot总是变绿,因为bot1.lua OnHit在最后加载的bot文件中。我想通过使用lua_newthread,我可以为每个“线程”定义一个新的OnHit创建的将为bot分配适当的颜色,因为在使用lua_dostring时,我使用了不同的lua_状态。但实际上,加载的最新OnHit将覆盖全局lua_状态环境中的前一个

我的问题是:如何为每个脚本创建不同的环境,以便为正确的bot->script->L调用正确的OnHit,并且我仍然可以访问在我创建的“全局”lua_状态环境中注册的所有函数(例如我的vec3、GetBot等…函数)

[编辑]

经过更多的研究,我想我需要的是能够在C语言中“沙盒”的能力。我说的对吗

[编辑]

实际上并不是真正的沙盒,因为我想知道,如果在脚本环境中查找失败,则会在全局环境中进行查找。甚至可能吗?

bot0.lua

local bot = {}

function bot:OnHit()
  self.color = vec3( 1.0, 0.0, 0.0)
end

return bot

bot1.lua

local bot = {}

function bot:OnHit()
  self.color = vec3( 0.0, 1.0, 0.0)
end

return bot

梅因·卢阿

all_bots = {[0]=require"bot0", require"bot1"}

function GetBot(name)
  if name == "bot #0" then
    return all_bots[0]
  elseif name == "bot #1" then
    return all_bots[1]
  end
end
C程序内部

luaL_dostring( bot->script->L, "GetBot('<the bot name>'):OnHit()" );
luaL\u dostring(bot->script->L,“GetBot(“”):OnHit()”;

这个问题可以通过OOP方法解决。让每个bot都是一个表,其中包含私有的
OnHit
函数,比如下面的
函数bot:OnHit()self.color=vec3(0.0,1.0,0.0)end
。然后只需调用
GetBot(\“\”):OnHit()
。我不确定我是否理解它,因为GetBot是一个返回bot指针的C函数……您能详细说明一下吗?根据您的脚本,
GetBot
是Lua函数。
luaL_dostring( bot->script->L, "GetBot('<the bot name>'):OnHit()" );