lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Javier Guerra wrote:

You have to understand that functions don't have names. numbers don't have names, strings don't have names. they're just values. any value can be referenced by any variable, or by a field in a table.

when you write

function f()
	print ("lalala")
end

in fact, you're writing:

_G["f"] = function ()
	print ("lalala")
end

there's nothing special about that 'f'. it's not a name, it's just the key in the global table that holds a reference to your function.

if you have a table with functions in them, they're not 'pointers' to some 'real' function variable, they're just as 'real' as the original variable.

for example, if you do:

t = {os.open}

then t[1] is a function, it's the same function as os.open, which by the way, is os['open']. os is a table, just like yours. you can even remove that function from it:

os.open = nil

and now t[1] is the only reference to that function.

of cource i understand this, sorry maybe my terminolgy was not right, it is all influence of C :)

now, back to your goal, that is to save tables... as Sergey suggested, you could search on several places to see if you find the very same function, then save how you got it, but it's not very general, since the function could have been removed, or maybe it was an 'anonymous' function.

maybe the easiest way would be to somehow get a hold of the original source code that created the reference. something like this: (untested!)

local reg
function getnamedval (s)
	local val = assert (loadstring ("return (".s.")")) ()
	reg [val]=s
	return val
end
function getvalname (v)
	return reg[v]
end

then, in your code, instead of directly copying a function (or any value), you call getnamedval():

t = { getnamedval("os.open"), getnamedval ("table.insert") }

t[1] and t[2] are functions, but now to save it you can do:

for _, v in pairs (t) do
	if type (v) == "function" then
		name = getvalname (v)
	end
end

and get the strings "os.open" and "table.insert" back.

thanks a lot i think it will help!


--
Шукай в телефонi мiй слiд...