others-How to solve the `attempt to index a number value (local 'self')` error when using lua?

1. Purpose

In this post I would demonstrate how to solve the following error when using lua to do objective programming:

/usr/local/bin/lua h4.lua
/usr/local/bin/lua: h4.lua:8: attempt to index a number value (local 'self')
stack traceback:
	h4.lua:8: in field 'withdraw'
	h4.lua:12: in main chunk
	[C]: in ?



2. The solution

2.1 The code

Here is the code, I tried to make an object Account using lua language:

Account = {balance=2}

function Account:withdraw(value)
    self.balance = self.balance-value
end

Users can withdraw money from the Account object . Then I test the above code:

local a = Account
a.withdraw2(1)
print("current balance",a.balance)



2.2 The error

When running the program, I got this error:

/usr/local/bin/lua h4.lua
/usr/local/bin/lua: h4.lua:8: attempt to index a number value (local 'self')
stack traceback:
	h4.lua:8: in field 'withdraw2'
	h4.lua:12: in main chunk
	[C]: in ?



2.3 The solution

TL;DR, here is the solution to the above error:

Change the code:

a.withdraw2(1)

to this:

a:withdraw2(1)


2.4 The theory

Why did this work?

The following code

function myTable:myFunction() end

is short (syntactic sugar) for

function myTable.myFunction(self) end

and the function call

myTable:myFunction()` is short for `myTable.myFunction(myTable)

When we call a.withdraw(2), the first parameter should be a table(self), not the number 2.


3. Summary

In this post, I demonstrated how to solve the attempt to index a number value (local 'self') error, the key point is to call the object’s method with a self parameter. That’s it, thanks for your reading.