Skip to content

Instantly share code, notes, and snippets.

@tbveralrud
Created January 25, 2018 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbveralrud/63ca0fbc34d92143d3b0ed8b4ff3b804 to your computer and use it in GitHub Desktop.
Save tbveralrud/63ca0fbc34d92143d3b0ed8b4ff3b804 to your computer and use it in GitHub Desktop.
lua4swift: General type checker for custom Lua Userdata types
import Lua
protocol CustomLuaBinding: CustomTypeInstance {
/// This is a 'type checker' function.
/// It is used to validate expected types when binding a method to a Lua-wrapped type.
///
/// e.g.
/// ```
/// type.createMethod([Foo.arg, Bar.arg, Baz.arg], _ fn: ....)
/// ```
/// ...where `Foo`, `Bar`, and `Baz` adopt `CustomLuaBinding`
///
/// - Note: This probably never needs to be explicitly implemented;
/// the generic solution provided in the protocol extension should suffice all possible custom types.
/// - Returns: `nil` if the value matches this type; or the name of this class for informing an unexpected type.
static func arg(_ vm: VirtualMachine, value: Value) -> String?
@discardableResult
static func addType(to vm: VirtualMachine) -> CustomType<Self>
}
extension CustomLuaBinding {
static func arg(_ vm: VirtualMachine, value: Value) -> String? {
guard value.kind() == .userdata, let userdata = value as? Userdata else { return luaTypeName() }
let instance: Self = userdata.toCustomType()
return type(of: instance) == self ? nil : luaTypeName()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment