This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
glopso's profile picture

Does LUA have definable classes?

Started by glopso, 12 July 2012 - 09:11 AM
glopso #1
Posted 12 July 2012 - 11:11 AM
Can I define classes in LUA?
Kolpa #2
Posted 12 July 2012 - 11:33 AM
u can define functions but thats about it :=

function pass()
return read("*")
end

print("enter your password")
password = pass()
print("your password is: "..password )
Xtansia #3
Posted 12 July 2012 - 12:03 PM
Can I define classes in LUA?

Firstly Lua is not an acronym so it is Lua not LUA.
Secondly no you cannot define classes in Lua
gmt2001 #4
Posted 12 July 2012 - 01:42 PM
You can store functions in a table and use that table to represent a class however there is no real classes.

example
MyMathClass = {
  Add = function (A, :)/>/>
	return A + B
  end,
  Subtract = function(A, B)/>/>
	return A - B
  end
}

print(MyMathClass.Add(1, 2)) -- prints 3
print(MyMathClass.Subtract(20, 5)) -- prints 15
Cloudy #5
Posted 12 July 2012 - 02:49 PM
Actually, it doesn't have built in classes. However, it is not difficult to create them yourself. Please see this page:

http://lua-users.org/wiki/SimpleLuaClasses

Meta tables FTW.
glopso #6
Posted 12 July 2012 - 03:46 PM
I was thinking of using tables to get what I want, but I wanted to know if there were already classes. Thanks to everyone who responded, and thanks for the tutorial, it should help.
kazagistar #7
Posted 12 July 2012 - 10:32 PM
Lua is a intentionally minimalist language. While it does not have classes per say, it does have all the syntactic sugar in place to very easily implement something akin to classes, and lets you do it in the way you find most convenient.

The basic idea is that the following lines are all equivalent:

person["doStuff"](person, place)
person.doStuff(person, place)
person:doStuff(place)
That last line is starting to look like an object method invocation, right?

So, one easy way to create a class is to make a table that has functions that all are defined so that they take a "self" object as their first parameter, and then make one of those functions a "clone" function which lets you create a copy of the table, and initialize whatever new values you want.

Do you not want to clone, or want advanced features like runtime-modifiable inheritance? For this, you can override the metatable function __index, so that it searches a "parent" table to see if the item is there, and otherwise returns the locally stored item. This sounds complex, but is actually pretty simple, basically a one liner.

The real question that I would ask in this case is why do you want classes?