在Lua中搜索表格(白名单)。

我一直在尝试为我的Garry's Mod服务器编写一个白名单附加组件。我对LUA还比较陌生,因此非常感谢任何帮助。我有一个想法,但我不知道该如何在其中搜索。比如我有一个表格:

local Table = { Player1, Player2, Player3 }
hook.Add( "PlayerConect", "Connect", function(ply)
       if ply:Nick() != Table then
       ply:Kick( "Reason here" )
   end
end)

这是我能理解如何做的范围之内。 谢谢你的宝贵时间。

点赞
用户1442917
用户1442917

我对 Garry's Mod 不是很熟悉,但如果你只需要检查玩家的昵称是否在表格中,你可以这样做:

local Table = { "Player1", "Player2", "Player3" }
hook.Add( "PlayerConect", "Connect", function(ply)
     local notfound = true
     -- 遍历表格中的所有元素
     for index, nick in ipairs(Table) do
       if ply:Nick() == nick then
         notfound = false
         break
       end
     end
     if notfound then ply:Kick( "Reason here" ) end
end)

如果你使用一个略微不同的表格来存储玩家的昵称,那么检查就会变得更简单(Table现在被用作哈希表):

local Table = { Player1 = true, Player2 = true, Player3 = true }
hook.Add( "PlayerConect", "Connect", function(ply)
     -- 检查昵称是否在表格中存在
     if not Table[ply:Nick()] then ply:Kick( "Reason here" ) end
end)
2015-02-24 06:35:17
用户4273199
用户4273199

创建一个白名单SteamID的表格(不要使用名称! 它们不是唯一的)

local WhitelistedIDs = {
  ["STEAM_0:0:52031589"] = true,
  ["STEAM_0:0:109379505"] = true,
  ["STEAM_0:0:115441745"] = true
}

然后编写你的代码,应该像这样

hook.Add( "PlayerInitialSpawn", "MyAwesomeWhitelist", function( --[[ Player ]] player)
if (~WhitelistedIDs[player::SteamID()]) then
   player:Kick( "Sorry! You are not Whitelisted!" )
end)

注意,我没有使用PlayerConnect钩子。我没有使用它,因为我们只有玩家的名字,但我们需要一个完整的玩家对象。

来源:我的经验和GMod Wiki

注:在示例中使用的SteamIDs都是我自己的有效帐户

代码未经测试,请在出现意外情况时留下评论

2015-06-22 12:35:39