Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

When I call a function that is in a module, it has 1 extra parameter that returns a table address?

So I have the script:

	v:Function(player, button)

and the module:

function v.Function(player, button)
	print("the test has passed")
	print(player)
	print(button)
end

(I omitted irrelevant code)

so basically when it prints, it prints a random table address for player and the player's name for the button.

BUT when I do this:

function testbutton.Function(playerr, player, button)
	print("the test has passed")
	print(player)
	print(button)
end

it works how I want it to. I know I can simply use the workaround, but can someone tell me why this happens? I doubt it's my code's fault, did I write the function in the module wrongly?

(im sorry i just took a ~2 month break from roblox lua)

1 answer

✓ Accepted answer

You're calling Function with the colon syntax, which means that Lua will automatically pass the table the function is defined in as the very first parameter. If you defined Function with the colon syntax, Lua would store the very same table value in a 'hidden' self variable.

local t = {
	a = function(str)
		print(self, str)
	end
}

function t:b(str)
	print(self, str)
end

function t.c(str)
	print(self, str)
end

t:a("1aaaa")
t:b("1bbbb")
t:c("1cccc")

print("\n")

t.a("2aaaa")
t.b("2bbbb")
t.c("2cccc")


--[[
nil	table: 0x23351f0
table: 0x23351f0	1bbbb
nil	table: 0x23351f0

nil	2aaaa
2bbbb	nil
nil	2cccc
]]

When we look at the first part of the output, we notice that the a and c functions don't have a value for the self variable. The b function instead does, as we defined and called it with the colon syntax. The table is sent implicitly and assigned to the self variable. Yet a and c receive the table as the parameter because we called it with the colon syntax.

The second part shows how a and c still have no value for the self variable, yet b does even though we called it with the dot syntax. This is because the very first parameter sent in a call to a member function that's defined with the colon syntax will be assigned to the self variable.

In short, calling a member function with the colon syntax is just syntactic sugar for tab.func(tab, ...).

1 comment

0

thank you so much

This discussion is preserved as it was. New answers, comments, and votes are closed.