Reputation: 53
trying to create a wrapper function to call various validation functions. The validation functions are not in the global namespace AND they require parameters. I'm using Lua 5.1 and trying to get the loadstring() function to work but not having any luck.
-- wrapper function
local function validateField(funcName, funcArg, errorTable)
local vres
local functionCall = loadstring("return " .. funcName .. "(...)")
vres = functionCall(funcArg)
if vres~=true then
table.insert(errorTable, vres)
return false
end
return true
end
calling code:
local result = validateField("valid.nameField" , data.name, errors)
Upvotes: 2
Views: 514
Reputation: 473232
If all you want to do is call a function, giving it some arguments, and checking the return value, then you don't need to use loadstring
at all. It's a simple matter of just passing the function as a parameter to validateField
.
local function validateField(errorTable, func, ...)
local res = func(...);
if res ~= true then
table.insert(errorTable, res)
return false
end
return true
end
And then calling it appropriately (note that I changed the order of parameters):
local result = validateField(errors, valid.nameField, data.name)
Upvotes: 3