Skip to content

Instantly share code, notes, and snippets.

@charles-l
Created July 19, 2014 19:27
Show Gist options
  • Save charles-l/f67e903fc1980586ce5f to your computer and use it in GitHub Desktop.
Save charles-l/f67e903fc1980586ce5f to your computer and use it in GitHub Desktop.
Cocoa Rectangle Drawing Example (with Lua objc FFI)
-- This gist uses http://luapower.com/objc.html as an FFI. I think it works on it's own, but I would recommend
-- getting the whole LuaPower project, because all the libraries rock.
--
-- This script will open a window that displays two rectangles. One red and one blue.
local glue = require'glue'
local objc = require'objc'
local ffi = require'ffi'
local pp = require'pp'
io.stdout:setvbuf'no'
io.stderr:setvbuf'no'
setmetatable(_G, {__index = objc})
objc.load'AppKit'
objc.load'Foundation'
local NSApp = class('NSApp', 'NSApplication <NSApplicationDelegate>')
function NSApp:applicationShouldTerminateAfterLastWindowClosed()
print'last window closed...'
collectgarbage()
return true
end
function NSApp:applicationShouldTerminate()
print'terminating...'
return true
end
local app = NSApp:sharedApplication()
app:setDelegate(app)
app:setActivationPolicy(NSApplicationActivationPolicyRegular)
local NSWin = class('NSWin', 'NSWindow <NSWindowDelegate>')
function NSWin:windowWillClose()
print'window will close...'
end
local style = bit.bor(NSTitledWindowMask, NSClosableWindowMask, NSMiniaturizableWindowMask, NSResizableWindowMask)
local win_rect = NSMakeRect(300, 300, 500, 300)
local win = NSWin:alloc():initWithContentRect_styleMask_backing_defer(win_rect, style, NSBackingStoreBuffered, false)
local view = NSView:alloc():initWithFrame(win_rect)
x = 10
function view:drawRect()
local myRect = NSMakeRect(x, 10, 100, 100)
local myRect2 = NSMakeRect(60, 60, 100, 100)
NSColor:blueColor():set()
NSRectFill(myRect)
NSColor:redColor():set()
NSRectFill(myRect2)
x = x + 1
print(x)
end
view:setNeedsDisplay(true)
win:setContentView(view)
win:setDelegate(win)
win:setTitle"Lua Rocks"
app:activateIgnoringOtherApps(true)
win:makeKeyAndOrderFront(nil)
app:run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment