Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created May 12, 2020 21:26
Show Gist options
  • Select an option

  • Save foxicode/4a3dca3a535e64a3dad4ac21f4d12240 to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/4a3dca3a535e64a3dad4ac21f4d12240 to your computer and use it in GitHub Desktop.
ViewController using Lua
import UIKit
import Lua
class LuaViewController: UIViewController {
@IBOutlet weak var vPluginContainer: UIView!
let vm = Lua.VirtualMachine()
var startFunc: Function?
var tickFunc: Function?
var timer: Timer?
private func loadLua() {
vm.globals["addWidget"] = vm.createFunction([
String.arg, // widget name
Int64.arg, // tag
Number.arg, // x coordinate
Number.arg, // y coordinate
Number.arg, // radius
String.arg // color hex string
]) { (args) -> SwiftReturnValue in
let (widgetName, widgetTag, xCoordinate, yCoordinate, radius, hexColor) = (
args.string, args.integer, args.number, args.number, args.number, args.string
)
switch widgetName {
case "Circle":
let v = UIView(frame: CGRect(
x: xCoordinate.toDouble() - radius.toDouble(),
y: yCoordinate.toDouble() - radius.toDouble(),
width: radius.toDouble() * 2,
height: radius.toDouble() * 2))
v.layer.cornerRadius = CGFloat(radius.toDouble())
v.tag = Int(widgetTag)
let uiColor = UIColor(hex: hexColor) ?? .black
v.backgroundColor = uiColor
self.vPluginContainer.addSubview(v)
default:
print("Unknown widget - \(widgetName)")
}
return .nothing
}
vm.globals["updateProperty"] = vm.createFunction([
Int64.arg, // tag
String.arg, // attribute name
String.arg // attribute value
]) { (args) -> SwiftReturnValue in
let (widgetTag, attributeName, attributeValue) = (
args.integer, args.string, args.string
)
guard let w = self.vPluginContainer.viewWithTag(Int(widgetTag)) else { return .nothing }
switch attributeName {
case "color":
if let color = UIColor(hex: attributeValue) {
w.backgroundColor = color
}
default:
break
}
return .nothing
}
guard let luaSourcePath = Bundle.main.path(forResource: "luaPluginCode", ofType: "lua") else {
print("LUA file not found")
return
}
do {
let luaCode = try String(contentsOfFile: luaSourcePath)
let result = vm.createFunction(luaCode)
switch result {
case .value(let f):
let fileRes = f.call([])
switch fileRes {
case .values(let values):
if values.count == 2 {
startFunc = values[0] as? Function
tickFunc = values[1] as? Function
} else {
print("Lua script must return 2 functions: start and tick")
}
case .error(let err):
print(err)
}
case .error(let err):
print(err)
}
}
catch {
print(error.localizedDescription)
}
}
@IBAction func runPlugin() {
loadLua()
_ = startFunc?.call([Double(vPluginContainer.bounds.width), Double(vPluginContainer.bounds.height)])
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
}
@objc func tick() {
_ = tickFunc?.call([10.0])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment