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

My metatable return nil, how to make that good?

I want to learn how to use metamethods but I don't understand the principle. The code belows not work, when I print a inexistant value the script return nil. But in the tutorial its working good, why? What I doesn't understand?

local myName = {  
josh = 10,  
tony = 15  
}

local yourName = {  
morice = 30  
}

local metamethod = {  
_index = myName.josh  
}

setmetatable(yourName, metamethod)  
print(yourName.josh) -- return nil

1 answer

✓ Accepted answer

The reasons for this


The two reasons for this are that

  • the index metamethod requires 2 underscores
  • if you are assigning a non-function value to the __index metamethod of a table, it has to be a table value

With that said, a quick fix for your script would be :

local myName = {
	josh = 10,
	tony = 15
}

  

local yourName = {
	morice = 30
}

  

local metamethod = {
	__index = myName
}

  

setmetatable(yourName, metamethod)
print(yourName.josh)

Hopefully this helped, be sure to accept if it did!

1 comment

0

Thanks you!:D

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