Log In  


Hello again, all! Here's a handy little function to make setting multiple values on an object less token intensive. quickset() is flexible and will properly identify strings, numbers, booleans and (basic 1-dimensional) tables.

It's only 74 tokens long (once you remove the assert(), which is useful for debugging!)

function quickset(obj, keys, vals)
	local v, k = split(vals), split(keys)
	-- remove/comment out the assert below before publication
	assert(#v == #k, "quickset() error: key/val count mismatch ("..#k.." keys, "..#v.." values)")
	for i=1,#k do
		local p,o = v[i]
		if p=="false" then 
			o=false
		elseif p=="true" then 
			o=true
		elseif tostr(p)[1] == "{" then
			o = split(sub(p, 2, -2),"|")
		else
			o = p
		end
		obj[k[i]]=o
	end
end

Usage

Instead of doing this:

-- this is 32 tokens worth of code

obj = {}
obj.x = 20
obj.y = 45
obj.first_name = "Steve"
obj.hp = 10
obj.gribbls = true
obj.table_stuff = {12,33,48,181,443}

do this:

-- this is only 8 tokens worth of code

obj = {}
quickset(obj, "x,y,first_name,hp,gribbls,table_stuff", "20,45,Steve,10,true,{12|33|48|181|443}")

This works particularly well in initialization routines, where you may need to be setting 15-20 different things at a time.



I use something kinda like this for my entity system.

(28 tokens, the global "e" is an alias for the current entry in the entity array)

function _set(s)
 local tbl=split(s)
 for i=2,#tbl,2 do
  e[tbl[i]]=tbl[i+1]
 end
end

Usage example (2 tokens):

_set"e,dx,0,dy,-2,hp,0"


[Please log in to post a comment]