Skip to content

Instantly share code, notes, and snippets.

@firedev
Last active April 22, 2020 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save firedev/02e8c43697bc8f4b70074d12f6d93c9a to your computer and use it in GitHub Desktop.
Save firedev/02e8c43697bc8f4b70074d12f6d93c9a to your computer and use it in GitHub Desktop.
PICO-8 Class-like Objects in pico-8 https://www.lexaloffle.com/bbs/?tid=2951

With the introduction of the function type() it is now possible to know the type of the variable.

So I tried to find a way to implement a simple class system and I think I found a way

First we need a function to copy tables

function copy(o)
  local c
  if type(o) == 'table' then
    c = {}
    for k, v in pairs(o) do
      c[k] = copy(v)
    end
  else
    c = o
  end
  return c
end

Then we can declare our objects the following way:

vec = {}
vec.x = 0
vec.y = 0
function vec:add(v)
  self.x += v.x
  self.y += v.y
end
function vec:subs(v)
  self.x -= v.x
  self.y -= v.y
end
function vec:mult(c)
  self.x *= c
  self.y *= c
end

To create multiple instances of vector, we just need to copy the object and edit it's attributes

a = copy(vec)
b = copy(vec)
a.x = 1
a.y = 2
b.x = 3
b.y = -1

And when we call the a:add(b) we get a.x == 4, a.y == 1

What's more we can define "subclass"

vec3 = copy(vec)
vec3.z = 0
function vec3:printz()
  print(self.z)
end

The function printz() will run just fine on copies of vec3 but will return an error on copies of vec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment