Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NanosUtils.ToBool and NanosUtils.AddAccessors #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion NanosUtils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,47 @@ function NanosUtils.FormatString(str, ...)
end

return str
end
end


-- converts any value to a boolean
function NanosUtils.ToBool(val)
if not val or (val == "false") or (val == 0) or (val== "0") then
return false
end

return true
end


-- add Get/Set functions to a provided table
local function valueToType(val, type)
if not type then return val end

if (type == "number") then return tonumber(val) end
if (type == "string") then return tostring(val) end
if (type == "boolean") then return NanosUtils.ToBool(val) end

return val
end

function NanosUtils.AddAccessors(table, name, key, type, default_fallback)
if not table or (type(table) ~= "table") or not name or not key then
return
end

name, key = tostring(name), tostring(key)

if table["Set" .. name] or table["Get" .. name] then
return
end

table["Set" .. name] = function(self, val)
self[key] = valueToType(val, type)
return self
end

table["Get" .. name] = function(self)
return (self[key] ~= nil) and self[key] or default_fallback
end
end