Tag Archives: metatable

A new, smarter way to create a Screen Manager

It hasn’t been a long time since Jim Bauwens surprised us with an elegant way to customize the gc object with your own functions. But he’s striking again.

Indeed, he came up with a new, smarter way to create a screen manager.
If you’re not familiar with this great concept, you should head over here.
For those who are, though, you should know that it’s all about thoroughly listing and linking all the events you’ll have defined later in each screen implementation.
For example :

function on.arrowKey(key) activeScreen:arrowKey(key) end
function on.timer() activeScreen:timer() end
 
-- long list of all handled events...       Then, somewhere else :
 
function myScreen:arrowKey(key)
    -- Your awesome code goes here
end
function myScreen:timer()
    print("I'm the myScreen timer, ticking....")
end
 
-- etc.

It sure works, but …. quite boring, eh ?

Well, let’s look at what Jim created.
I define (t)his new screen manager concept as “Smarter” because with this code, you won’t even have to directly (explicitly) rely on the traditional event handling you’re used to, writing things like on.arrowKey, on.enterKey… or the good old on.paint.
That’s right, with this new method : no more “function on.paint(gc) …” etc.

“What’s this sorcery about ?” , you may wonder ?
Well, once more, it’s all about intelligently using the power of Lua metatables.
In short, metatables are sets of properties defining an object (generally a table) ‘s behaviour.
There is a “__index” property that you can define, that will describe how the table will react when the script calls an undefined element of that table. Pretty useful, believe me.
Well, the thing is that when you write “function on.paint(gc)”, you’re actually defining the “paint” method of the “on” table (thus the dot).
What we want to do, is to get rid of the explicit definition and to “redirect” the paint event to whichever screen we want to.
So, we’re going to use an “eventDistributer” method that takes as arguments whatever its passed, with the use of the “…” (the event followed by its parameters, if any), and “passes” them to the screen we want (checking that the event actually exists (defined) for the screen :

local triggeredEvent = "paint"  -- first declaration, it will be overwritten anyway
local eventDistributer = function (...)
     local currentScreen = GetScreen()
     if currentScreen[triggeredEvent] then
         currentScreen[triggeredEvent](currentScreen, ...)
     end
end

This code should be rather clear to you now.

Now, what we have to do is to actually bind that function to the “on” ‘s metatable __index (notice the smart use of closures) :

local eventCatcher = {}
 
eventCatcher.__index = function (tbl, event)
    triggeredEvent = event
    return eventDistributer
end
 
setmetatable(on, eventCatcher)

That code tells the Lua script that whenever an event without an explicit “on.xxx” handler occurs, it will execute this function (which returns the function – that’s the closure I was talking about – that will take the args of the event and pass it through the eventDistributer thus actually calling the correct screen’s appropriate event handler). You might find all this confusing, but at some point you sould be able to figure it out 🙂

Anyway, here’s the full code for the screen manager and event redistributer.
(You’ll still need to create (and push) your screens as usual.)

local screens = {}
local screenLocation = {}
local currentScreen = 0
 
function RemoveScreen(screen)
    screen:removed()
    table.remove(screens, screenLocation[screen])
    screenLocation[screen] = nil
    currentScreen = #screens -- sets the current screen as the top one on the stack.
    if #screens<=0 then print("Uh oh. This shouldn't have happened ! You must have removed too many screens.") end
end
 
function PushScreen(screen)
    -- if already activated, remove it first (so that it will be on front later)
    if screenLocation[screen] then
        RemoveScreen(screen)
    end
 
    table.insert(screens, screen)
    screenLocation[screen] = #screens
 
    currentScreen = #screens
    screen:pushed()
end
 
function GetScreen()
    return screens[currentScreen] or RootScreen
end
 
Screen = class()
 
function Screen:init() end
 
function Screen:pushed() end
function Screen:removed() end
 
RootScreen = Screen() -- "fake", empty placeholder screen.
 
local eventCatcher = {}
local triggeredEvent = "paint"
 
local eventDistributer = function (...)
     local currentScreen = GetScreen()
     if currentScreen[triggeredEvent] then
         currentScreen[triggeredEvent](currentScreen, ...)
     end
end
 
eventCatcher.__index = function (tbl, event)
    triggeredEvent = event
    return eventDistributer
end
 
-- finally linking everything
setmetatable(on, eventCatcher)

I’m sure a lot of you readers love a working .tns example directly, so, I made one just for you : click here. It’s a simple example showing a few events, without a single on.xxxx event handler explicitely defined, inside 2 screens. I’ve commented the code quite well so you’d understand quickly, I’m sure 🙂

For a more “real-life” example fully demonstrating this technique (as well as the gc-customizing trick), I suggest downloading Jim’s Memory game here.

 

How to add your own functions to “gc”

Hi all,

As you know, in order to do graphical things in Lua on the Nspire platform, you have to deal with gc and its methods TI created, like drawString, drawRect, fillArc, etc.

Well, what if you wanted to make a drawRoundRect routine ?

You could certainely do something like :

function drawRoundRect(gc, x, y, wd, ht, rd)
        if rd > ht/2 then rd = ht/2 end
        gc:drawLine(x + rd, y, x + wd - (rd), y)
        gc:drawArc(x + wd - (rd*2), y + ht - (rd*2), rd*2, rd*2, 270, 90)
        gc:drawLine(x + wd, y + rd, x + wd, y + ht - (rd))
        gc:drawArc(x + wd - (rd*2), y, rd*2, rd*2,0,90)
        gc:drawLine(x + wd - (rd), y + ht, x + rd, y + ht)
        gc:drawArc(x, y, rd*2, rd*2, 90, 90)
        gc:drawLine(x, y + ht - (rd), x, y + rd)
        gc:drawArc(x, y + ht - (rd*2), rd*2, rd*2, 180, 90)
end
 
function on.paint(gc)
        drawRoundRect(gc, 100, 50, 20, 15, 5)
        ...
end

Indeed, that works.

But wouldn’t it be cool to actually have it like, “gc:drawRoundRect(100,50,20,15,5)”, so it can feel way more natural and wouldn’t need you to explicitely pass gc as an argument ? 😉
Well, here is the definitive solution to this, by Jim Bauwens 😉

function AddToGC(key, func)
        local gcMetatable = platform.withGC(getmetatable)
        gcMetatable[key] = func
end
 
local function drawRoundRect(gc, x, y, wd, ht, rd)
        -- the code above
end
 
AddToGC("drawRoundRect", drawRoundRect)
 
function on.paint(gc)
        gc:drawRoundRect(100, 50, 20, 15, 5)
        ...
end

One more thing :

You may have noticed the use platform.withGC, which is an API “2.0”+ (OS 3.2+) function. Here’s how to “recreate” it for earlier versions :

if not platform.withGC then
        platform.withGC = function(func, ...)
            local gc = platform.gc()
            gc:begin()
            func(..., gc)
            gc:finish()
        end
    end

[Update] : John Powers from TI commented that this definition of platform.withGC has some limitations, and proposed this better version (thanks !) :

if not platform.withGC then
    function platform.withGC(f)
        local gc = platform.gc()
        gc:begin()
        local result = {f(gc)}
        gc:finish()
        return unpack(result)
    end
end