Automation with Lua
Automation with Lua Cocoa
All of the previous examples were coded in scripting languages that ship as part of OS X. KosmicTask uses a plug-in architecture to implement its language support enabling it to encompass a wide range of different language types and configurations. In the case of those languages that are included as part of OS X the KosmicTask language plug-in merely exposes the underlying language to the application. But KosmicTask also supports scripting in languages that come embedded in the language plug-in itself.
Lua is a powerful, fast, lightweight scripting language. As in the case of JavaScript KosmicTask includes support for two variants of Lua. In both of these cases language support is embedded in the relevant plug-in.
The first variant, Lua, supports all the features of standard Lua and KosmicTask includes a standard range of useful templates. The second variant, LuaCocoa, is a Cocoa bridge. Hence we should be able to rework our Pages task in Lua.
LuaCocoa.import("ScriptingBridge")
function kosmicTask(pagesDocFilePath)
-- use the ScriptingBridge framework to access the application
local app = SBApplication:applicationWithBundleIdentifier_("com.apple.iWork.pages")
local rtfDocFilePath = pagesDocFilePath .. ".rtf"
-- open pages
local myDoc = app:open_(pagesDocFilePath)
-- save document
myDoc:saveAs_in_("SLDocumentTypeRichText", rtfDocFilePath)
-- close document
myDoc:closeSaving_savingIn_(false, nil)
-- get the kosmicTaskController class
local taskController = NSClassFromString("KosmicTaskController")
-- get our result file path
-- this file will be automatically deleted when the task ends.
local resultFile = taskController:resultFileWithName_('result.html')
resultFile = tostring(resultFile) -- get a native lua string
-- convert our file
local cmd = string.format("textutil -convert html -output \"%s\" \"%s\"", resultFile, rtfDocFilePath)
os.execute(cmd)
-- return file content in native Lua dictionary
local result = {}
result.kosmicFile = resultFile
return result
end
As in the case of JavaScript Cocoa we use the KosmicTaskController to retrieve a result file name. The object is not automatically available but is retrieved using the Cocoa framework function NSClassFromString(). This approach is used in several of the Cocoa bridges and is demonstrated where appropriate in the usage documents and templates.
This example also makes use of another feature of Cocoa bridging - the ability to return native scripting language objects as results. Previously we had either printed our YAML formatted results directly or returned them as the result of calling the task function. With the Cocoa bridge in place we can form our result in a native data structure, a dictionary in this case, and return that as our result. This means that the task can manipulate its result as an object which makes returning results with a complex structure easy.
