Skip to content

API Additional Lua Features

THE_ORONCO edited this page May 19, 2022 · 2 revisions

Additional Lua Features

PICO-8 also exposes 2 features of Lua for advanced users: Metatables and Coroutines.

For more information, please refer to the Lua 5.2 manual.

Metatables

Metatables can be used to define the behaviour of objects under particular operations. For example, to use tables to represent 2D vectors that can be added together, the '+' operator is redefined by defining an "__add" function for the metatable:

VEC2D={
    __ADD=FUNCTION(A,B) 
    RETURN {X=(A.X+B.X), Y=(A.Y+B.Y)} 
    END
}
    
V1={X=2,Y=9} SETMETATABLE(V1, VEC2D)
V2={X=1,Y=5} SETMETATABLE(V2, VEC2D)
V3 = V1+V2
PRINT(V3.X..","..V3.Y) -- 3,14

SETMETATABLE(TBL, M)

Set table TBL metatable to M

GETMETATABLE(TBL)

return the current metatable for table t, or nil if none is set

RAWSET(TBL, KEY, VALUE)

RAWGET(TBL, KEY)

RAWEQUAL(TBL1,TBL2

RAWLEN(TBL)

Raw access to the table, as if no metamethods were defined.

Function Arguments

The list of function arguments can be specified with ...

FUNCTION PREPRINT(PRE, S, ...)
    LOCAL S2 = PRE..TOSTR(S)
    PRINT(S2, ...) -- PASS THE REMAINING ARGUMENTS ON TO PRINT()
END

To accept a variable number of arguments, use them to define a table and/or use Lua's select() function. select(index, ...) returns all of the arguments after index.

FUNCTION FOO(...)
    LOCAL ARGS={...} -- BECOMES A TABLE OF ARGUMENTS
    FOREACH(ARGS, PRINT)
    ?SELECT("#",...)    -- ALTERNATIVE WAY TO COUNT THE NUMBER OF ARGUMENTS
    FOO2(SELECT(3,...)) -- PASS ARGUMENTS FROM 3 ONWARDS TO FOO2()
END

Coroutines

Coroutines offer a way to run different parts of a program in a somewhat concurrent way, similar to threads. A function can be called as a coroutine, suspended with

YIELD() any number of times, and then resumed again at the same points

FUNCTION HEY()
    PRINT("DOING SOMETHING")
    YIELD()
    PRINT("DOING THE NEXT THING")
    YIELD()
    PRINT("FINISHED")
END
         
C = COCREATE(HEY)
FOR I=1,3 DO CORESUME(C) END

COCREATE(F)

Create a coroutine for function f.

CORESUME(C, [P0, P1 โ€ฆ])

Run or continue the coroutine c. Parameters p0, p1โ€ฆ are passed to the coroutine's function.

Returns true if the coroutine completes without any errors Returns false, error_message if there is an error.

** Runtime errors that occur inside coroutines do not cause the program to stop running. It is a good idea to wrap CORESUME() inside an @ASSERT(). If the assert fails, it will print the error message generated by coresume.

ASSERT(CORESUME(C))

COSTATUS(C)

Return the status of coroutine C as a string:

  • "running"
  • "suspended"
  • "dead"

YIELD

Suspend execution and return to the caller.

Clone this wiki locally