Is there a way to implement a mechanism similar to python’s __getitem__?
for instance, having the following:
local t1 = {a=1, b=2, c=3, d=4}
if in code, t1.e will be called, then I wish to have something else returned rather than nil
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use
setmetatableand the__indexmetamethod:Note that this will not be called when you do
t.nonexistant = something. For that, you need the__newindexmetamethod: