garrysmod icon indicating copy to clipboard operation
garrysmod copied to clipboard

Add default value and custom validators to AccessorFunc

Open LeQuackers opened this issue 4 years ago • 1 comments

As the title states. Default values are nice and custom validators would be very useful.

Some examples:

local tab = {}


function FORCE_PLAYER(v)
	return isentity(v) and v:IsValid() and v:IsPlayer() and v or NULL
end
AccessorFunc(tab, "m_Player", "Player", FORCE_PLAYER, NULL)
tab:SetPlayer(player.GetAll()[1])
tab:SetPlayer("lol")
tab:SetPlayer(5)


function FORCE_STEAMID(v)
	return string.match(tostring(v), "^STEAM_[0-5]:[01]:%d+$") or "UNKNOWN"
end
AccessorFunc(tab, "m_SteamID", "SteamID", FORCE_STEAMID, "")
tab:SetSteamID("STEAM_1:1:123456")
tab:SetSteamID("STEAM_9:1:123456")
tab:SetSteamID("STEAM_1:1:")


function FORCE_BETWEEN(a, b)
	return function(v) return math.Clamp(tonumber(v), a, b) end
end
AccessorFunc(tab, "m_Test", "Test", FORCE_BETWEEN(5, 10), 1)
tab:SetTest(2)
tab:SetTest(7)
tab:SetTest(13)


PrintTable(tab)

LeQuackers avatar Oct 10 '20 05:10 LeQuackers

Considering the usual usage of this function, the default argument will simply not work.

E.g. https://github.com/Facepunch/garrysmod/blob/master/garrysmod/lua/vgui/dcolorbutton.lua#L6

robotboy655 avatar Dec 17 '20 19:12 robotboy655