Wiki

Clone wiki

Core / Codea Code Snippets

To Array function - shallow copies a Key value Table to indexed array table

function toarray(...)
    local new = {}
    local tbl
    if #arg == 1 and type(arg[1]) == "table" then tbl = arg[1]
    else tbl = arg end
    local count = 1
    for i,v in pairs(tbl) do
        new[count] = v
        count = count + 1
    end
    return new
end

To lookup function - Shallow copies an indexed array to a key - value lookup table

function tolookup(tbl,id)
    local new ={}
    if type(id) == "string" then
        for i,v in pairs(tbl) do new[v[id]] = v end
    elseif type(id) == "table" then
        local count = 1
        for i,v in pairs(tbl) do
            new[id[count]] = v
            count = count + 1
        end
    end
    return new
end

Callback to an instance / function which uses self within a class

local callback = function(...) self:mycallback(...) end

Using self in loadstring

ClassTest = class()

function ClassTest:init(x)
    -- you can accept and set parameters here
    self.x = x

end

function ClassTest:test()
    loadstring("return function(self) print(self.x) end")()(self)
end

test = ClassTest("testclass")
test:test() -- prints 'testclass'

Perform calculation in the output window in a running Codea program

return 3 * 5

Using inheritance for a human and computer player - example is in context to a battleships game

Player=class()

function Player:init()
end

function Player:setup()
-- get notification of new game
end

function Player:place(ship)
end

function Player:fireat(player,square)
end

function Player:moveStarted()
-- get notification of turn
end
function Player:moveFinished()
-- notify turn finished
end

function Player:touched(touch)
end
HumanPlayer = class(Player)
function HumanPlayer:init()
    Player.init(self)
end

function HumanPlayer:touched(touch)
     self:place(ship)
     self:fireat(opponent,touchedSquare)
     self:moveFinished()
end
ComputerPlayer = class(Player)
function ComputerPlayer:init()
     Player.init(self)
end
function ComputerPlayer:setup()
-- choose strategy 
-- place ships
end
function ComputerPlayer:moveStarted()
-- calculate move / best move
--  do move 
self:MoveFinished()
end




Adding more snippets

  1. you need a basic bitbucket account
  2. then you get the option to edit this page
  3. select Creole (instead of markdown) from the dropdown next to Preview at top right of the text editor
  4. Creole formatting rules are here
  5. to embed code, put three { in front, followed by #!lua on the next line, then the code, then three } at the end

    And before you ask, there seems to be no way to create internal page hyperlinks, so we could just put a list of questions at the top with links to detailed answers below (if you find a way, please explain it here!).

Updated