How do you parse self in a __index function?

I’m trying to make a __index function using Self. The problem is that instead of using the table I created, it uses the original module.

local plr = setmetatable({}, {__index = function(self, func)
     local foundfunc = self.Character[func]
     return foundfunc
end})

--I would essentially be trying to do
self:Tadah()--tadah does not exist in the player class, so look for it in the character class instead
--self instead simply represents plr, without all of the data declared in .New()

As far as I know I need to have a function to search within another table since the Character class is unique for each and every single player.

What do I do? Why isn’t it parsing self?

1 Like

In this context self is just a “normal” variable, it isn’t (ever) a global variable or a keyword, so you would have to define it like a “normal” variable.

In terms of solving your actual problem though, if i understand correctly, you wouldn’t need a function to search within the character class, instead you can just add the __index method into the character class itself and set it as the metatable of plr:

--Example
local Character = {}
Character.__index = Character

function Character:Tadah()
  print(self) --self is defined here because of the ":" syntax
end

local plr = setmetatable({},Character)
plr.Tadah(2)

*I’m also assuming that plr is being created for each player.


1 Like

I needed it to specifically run a function because the function i was trying to run was inside of self.Character, which was unique to each and every single player. Your answer wasn’t really helping address this issue. But no matter, figured out how to do it!

local plr = setmetatable({}, {__index = function(list, func)
	return function(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
		self.Character[func](self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
	end
end})
--we now have self within the function
2 Likes

Great! I would recommend using “…” for that function though, it might make things a little more scalable and perhaps readable:

return function(self, ...)
	self.Character[func](self, ...)
end
1 Like

My code isn’t going to be written in tables, though. I tested to see if … automatically packed everything inside of a table, and perhaps I could unpack it, but it just said that it expected a table and got a string (a regular variable just called …)

That might be because you tried to use the vardiac argument as a single variable, i meant doing something like:

local function TestFunc(a,b,c)
	print(a,b,c) -- 2 3 1
end

local function pass(a,...)
	TestFunc(a,...)
end

pass(2,3,1)

See Variadic Functions


But either way your solution works too

1 Like

No, I passed more than one variable. I don’t know why it didn’t work.
Edit: Nvm, figured it out.

1 Like