How to get the name of a variable to a string?

Okay this might not be possible and probably is way out of reach for Lua but I want to get the name if a variable/function/table, for example:

local a = function ()
	return "yes"
end

print(tostring(a))

I want it to print β€œa” but it prints:

function: 0x639a0eedbdc14364

Instead.

How could I do this?

The two methods I know are:

debug.info(func,"n")

and

next(getfenv(func))

Neither of which are particularly useful in all practicality but
Theres probably a better way anyways

None of those worked. Can you provide a example of these printing something?

My mistake, the second one only works in the command line
The first one should work properly though
Its definitely not best practice to use debug functions in your main game script though, I would personally put the function in a table or find some other way to solve the problem (not involving getting the functions name)

Heres code that worked for debug.info just in case

function func()
	print("test")
end

print(debug.info(func,"n"))
1 Like
local a = {"a", function()
    return "yes"
end}

print(a[1])
print(a[2]())

that should print β€œa”
and then β€œyes”

there are many other ways to do this with a table, this is just one of the ways

why use a table? well that means you don’t need debug or getfenv

EDIT: changed the table name to β€œa” since the function from the original post was named β€œa”

2 Likes