我想知道是否有可能基于函数的参数从表中选择一个值。
我尝试过静态设置值,然后返回该值。我只想使用函数参数来做到这一点。
function CheckWeapon(ped, attachment)
for k,v in pairs(weapons)do
if GetHashKey(k) == GetSelectedPedWeapon(ped) then
print(v.attachment)
return v.attachment -- This needs to be based on the
-- argument "attachment"
end
end
return false
end
Run Code Online (Sandbox Code Playgroud)
我希望,如果我向该函数提供参数“ silencer”,我将在表中收到相应的消音器值。相反,它为零。如果我手动键入return v.silencer,它仍然可以工作。
在Lua中,您可以使用2种方式对表建立索引。
完成后,您可以使用.诸如,sometable.key
但是这只是另一种索引方法的语法糖,sometable["key"]
这两种方法都使用字符串key对表进行索引。
您的代码可能如下所示:
function CheckWeapon(ped, key)-- where key is a string ie: "attachment"
for k,v in pairs(weapons)do
if GetHashKey(k) == GetSelectedPedWeapon(ped) then
print(v[key])
return v[key]
end
end
return false
end
Run Code Online (Sandbox Code Playgroud)
使用sometable["key"]选项还允许为无法访问键.如
sometable["my key"] -- note the space
sometable["1st_key"] -- note it begins with a number
Run Code Online (Sandbox Code Playgroud)