Roblox Luau调用Database报Attempt to call a nil value错误求助
错误核心原因
- 遍历方法用错:你使用
ipairs遍历dbFunctions表,但ipairs仅支持遍历数字索引的数组结构,你定义的Set是字符串键的成员,遍历逻辑完全不会执行到,导致new.Set从未被赋值,调用就会报nil错误。 - 多余的协程包裹:你把方法绑定逻辑放在了协程中异步执行,会出现
new表已经返回给调用方,方法绑定逻辑还没执行的时序问题,同样会触发nil报错。
修复后的模块脚本代码
--Variables local dss = game:GetService("DataStoreService") -- Tables local greenwich = {} local dbFunctions = {} --Functions function greenwich:GetDB(name) local db = dss:GetDataStore(name) local new = {} new.store = db -- 移除协程,改用pairs遍历字符串键的方法表 for k, v in pairs(dbFunctions) do new[k] = function(...) local args = { ... } -- 增加return透传方法返回值,满足你获取返回值的需求 return v(new.store, unpack(args)) end end print(new.store.Name, name) return new end function dbFunctions:Set(store, key, value) print(value) -- 后续可在此处添加实际的DataStore存储逻辑,例如 store:SetAsync(key, value) return value end --Returning everything. return greenwich
验证说明
修改后你原有的调用逻辑ModuleScript:GetDB("salvage").Set("key", "value")可以正常执行,也会正确返回你传入的value值。
内容的提问来源于stack exchange,提问作者Noobie
相关产品推荐
相关产品推荐

