diff --git a/src/util/libbl.lua b/src/util/libbl.lua index efd5889..237d59c 100644 --- a/src/util/libbl.lua +++ b/src/util/libbl.lua @@ -10,182 +10,188 @@ bl = bl or {} -- Misc -- Apply a function to each element in a list, building a new list from the returns -local function map(t,f) - local u = {} - for i,v in ipairs(t) do - u[i] = f(v) - end - return u +local function map(t, f) + local u = {} + for i, v in ipairs(t) do + u[i] = f(v) + end + return u end local function isValidFuncName(name) - return type(name)=='string' and name:find('^[a-zA-Z0-9_]+$') + return type(name) == 'string' and name:find('^[a-zA-Z0-9_]+$') end local function isValidFuncNameNs(name) - return type(name)=='string' and ( - name:find('^[a-zA-Z0-9_]+$') or - name:find('^[a-zA-Z0-9_]+::[a-zA-Z0-9_]+$') ) + return type(name) == 'string' and ( + name:find('^[a-zA-Z0-9_]+$') or + name:find('^[a-zA-Z0-9_]+::[a-zA-Z0-9_]+$')) end local function isValidFuncNameNsArgn(name) - return type(name)=='string' and ( - name:find('^[a-zA-Z0-9_]+$') or - name:find('^[a-zA-Z0-9_]+%.[a-zA-Z0-9_]+$') or - name:find('^[a-zA-Z0-9_]+::[a-zA-Z0-9_]+$') or - name:find('^[a-zA-Z0-9_]+:[0-9]+$') or - name:find('^[a-zA-Z0-9_]+::[a-zA-Z0-9_]+:[0-9]+$') ) + return type(name) == 'string' and ( + name:find('^[a-zA-Z0-9_]+$') or + name:find('^[a-zA-Z0-9_]+%.[a-zA-Z0-9_]+$') or + name:find('^[a-zA-Z0-9_]+::[a-zA-Z0-9_]+$') or + name:find('^[a-zA-Z0-9_]+:[0-9]+$') or + name:find('^[a-zA-Z0-9_]+::[a-zA-Z0-9_]+:[0-9]+$')) end -- Whether a var can be converted into a TS vector local function isTsVector(val) - if type(val)~='table' then return false end - if #val~=3 and #val~=2 then return false end - if val.__is_vector then return true end - for _,v in ipairs(val) do - if type(v)~='number' then return false end - end - return true + if type(val) ~= 'table' then return false end + if #val ~= 3 and #val ~= 2 then return false end + if val.__is_vector then return true end + for _, v in ipairs(val) do + if type(v) ~= 'number' then return false end + end + return true end -- Use strings for object types instead of integer bitmasks like in TS local tsTypesByName = { - ['all'] = -1, - ['static'] = 1, - ['environment'] = 2, - ['terrain'] = 4, - ['water'] = 16, - ['trigger'] = 32, - ['marker'] = 64, - ['gamebase'] = 1024, - ['shapebase'] = 2048, - ['camera'] = 4096, - ['staticshape'] = 8192, - ['player'] = 16384, - ['item'] = 32768, - ['vehicle'] = 65536, - ['vehicleblocker'] = 131072, - ['projectile'] = 262144, - ['explosion'] = 524288, - ['corpse'] = 1048576, - ['debris'] = 4194304, - ['physicalzone'] = 8388608, - ['staticts'] = 16777216, - ['brick'] = 33554432, - ['brickalways'] = 67108864, - ['staticrendered'] = 134217728, - ['damagableitem'] = 268435456, + ['all'] = -1, + ['static'] = 1, + ['environment'] = 2, + ['terrain'] = 4, + ['water'] = 16, + ['trigger'] = 32, + ['marker'] = 64, + ['gamebase'] = 1024, + ['shapebase'] = 2048, + ['camera'] = 4096, + ['staticshape'] = 8192, + ['player'] = 16384, + ['item'] = 32768, + ['vehicle'] = 65536, + ['vehicleblocker'] = 131072, + ['projectile'] = 262144, + ['explosion'] = 524288, + ['corpse'] = 1048576, + ['debris'] = 4194304, + ['physicalzone'] = 8388608, + ['staticts'] = 16777216, + ['brick'] = 33554432, + ['brickalways'] = 67108864, + ['staticrendered'] = 134217728, + ['damagableitem'] = 268435456, } local tsTypesByNum = {} -for k,v in pairs(tsTypesByName) do - tsTypesByNum[v] = k +for k, v in pairs(tsTypesByName) do + tsTypesByNum[v] = k end -- Type conversion local toTsObject -- Convert a string from TS into a boolean -- Note: Nonempty nonnumeric strings evaluate to 1, unlike in TS -local function tsBool(v) return v~='' and v~='0' end +local function tsBool(v) return v ~= '' and v ~= '0' end -- Convert a Lua var into a TS string, or error if not possible local function valToTs(val) - if val==nil then -- nil -> '' - return '' - elseif type(val)=='boolean' then -- bool -> 0 or 1 - return val and '1' or '0' - elseif type(val)=='number' then -- number - return tostring(val) - elseif type(val)=='string' then -- string - return val - elseif type(val)=='table' then - if val._tsObjectId then -- object -> object id - return tostring(val._tsObjectId) - elseif isTsVector(val) then -- vector - > 3 numbers - return table.concat(val, ' ') - elseif #val==2 and isTsVector(val[1]) and isTsVector(val[2]) then - -- box - > 6 numbers - return table.concat(val[1], ' ')..' '..table.concat(val[2], ' ') - else - error('valToTs: could not convert table', 3) - end - else - error('valToTs: could not convert '..type(val), 3) - end + if val == nil then -- nil -> '' + return '' + elseif type(val) == 'boolean' then -- bool -> 0 or 1 + return val and '1' or '0' + elseif type(val) == 'number' then -- number + return tostring(val) + elseif type(val) == 'string' then -- string + return val + elseif type(val) == 'table' then + if val._tsObjectId then -- object -> object id + return tostring(val._tsObjectId) + elseif isTsVector(val) then -- vector - > 3 numbers + return table.concat(val, ' ') + elseif #val == 2 and isTsVector(val[1]) and isTsVector(val[2]) then + -- box - > 6 numbers + return table.concat(val[1], ' ') .. ' ' .. table.concat(val[2], ' ') + else + error('valToTs: could not convert table', 3) + end + else + error('valToTs: could not convert ' .. type(val), 3) + end end local fromTsForceTypes = { - ['boolean'] = tsBool, - ['object'] = function(val) toTsObject(val) end, -- toTsObject not defined yet - ['string'] = tostring, + ['boolean'] = tsBool, + ['object'] = function(val) toTsObject(val) end, -- toTsObject not defined yet + ['string'] = tostring, } local function convertValFromTs(val, typ) - return fromTsForceTypes[typ](val) or - error('valFromTs: invalid force type '..typ, 4) + return fromTsForceTypes[typ](val) or + error('valFromTs: invalid force type ' .. typ, 4) end bl._forceType = bl._forceType or {} local function valFromTs(val, name, name2) -- todo: ensure name and name2 are already lowercase - if type(val)~='string' then - error('valFromTs: expected string, got '..type(val), 3) end - if name then - name = name:lower() - if bl._forceType[name] then - return convertValFromTs(val, bl._forceType[name]) - end - end - if name2 then - name2 = name2:lower() - if bl._forceType[name2] then - return convertValFromTs(val, bl._forceType[name2]) - end - end - -- '' -> nil - if val=='' then return nil end - -- number - local num = tonumber(val) - if num then return num end - -- vector - local xS,yS,zS = val:match('^(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+)$') - if xS then return vector{tonumber(xS),tonumber(yS),tonumber(zS)} end - local x1S,y1S,z1S,x2S,y2S,z2S = val:match( - '^(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+) '.. - '(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+)$') - -- box (2 vectors) - if x1S then return { - vector{tonumber(x1S),tonumber(y1S),tonumber(z1S)}, - vector{tonumber(x2S),tonumber(y2S),tonumber(z2S)} } end - -- string - return val + if type(val) ~= 'string' then + error('valFromTs: expected string, got ' .. type(val), 3) + end + if name then + name = name:lower() + if bl._forceType[name] then + return convertValFromTs(val, bl._forceType[name]) + end + end + if name2 then + name2 = name2:lower() + if bl._forceType[name2] then + return convertValFromTs(val, bl._forceType[name2]) + end + end + -- '' -> nil + if val == '' then return nil end + -- number + local num = tonumber(val) + if num then return num end + -- vector + local xS, yS, zS = val:match('^(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+)$') + if xS then return vector { tonumber(xS), tonumber(yS), tonumber(zS) } end + local x1S, y1S, z1S, x2S, y2S, z2S = val:match( + '^(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+) ' .. + '(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+)$') + -- box (2 vectors) + if x1S then + return { + vector { tonumber(x1S), tonumber(y1S), tonumber(z1S) }, + vector { tonumber(x2S), tonumber(y2S), tonumber(z2S) } } + end + -- string + return val end local function arglistFromTs(name, argsS) - local args = {} - for i,arg in ipairs(argsS) do - args[i] = valFromTs(arg, name..':'..i) - end - return args + local args = {} + for i, arg in ipairs(argsS) do + args[i] = valFromTs(arg, name .. ':' .. i) + end + return args end local function arglistToTs(args) - return map(args, valToTs) + return map(args, valToTs) end local function classFromForceTypeStr(name) - local class, rest = name:match('^([a-zA-Z0-9_]+)(::.+)$') - if not class then - class, rest = name:match('^([a-zA-Z0-9_]+)(%..+)$') end - return class,rest + local class, rest = name:match('^([a-zA-Z0-9_]+)(::.+)$') + if not class then + class, rest = name:match('^([a-zA-Z0-9_]+)(%..+)$') + end + return class, rest end local setForceType setForceType = function(ftname, typ) - if typ~=nil and not fromTsForceTypes[typ] then - error('bl.type: invalid type \''..typ..'\'', 2) end - if not isValidFuncNameNsArgn(ftname) then - error('bl.type: invalid function or variable name \''..ftname..'\'', 2) end - - ftname = ftname:lower() - - bl._forceType[ftname] = typ - - -- apply to child classes if present - local cname, rest = classFromForceTypeStr(ftname) - if cname then - local meta = bl._objectUserMetas[cname] - if meta then - for chcname,_ in pairs(meta._children) do - setForceType(chcname..rest, typ) - end - end - end + if typ ~= nil and not fromTsForceTypes[typ] then + error('bl.type: invalid type \'' .. typ .. '\'', 2) + end + if not isValidFuncNameNsArgn(ftname) then + error('bl.type: invalid function or variable name \'' .. ftname .. '\'', 2) + end + + ftname = ftname:lower() + + bl._forceType[ftname] = typ + + -- apply to child classes if present + local cname, rest = classFromForceTypeStr(ftname) + if cname then + local meta = bl._objectUserMetas[cname] + if meta then + for chcname, _ in pairs(meta._children) do + setForceType(chcname .. rest, typ) + end + end + end end bl.type = setForceType @@ -193,787 +199,859 @@ bl.type = setForceType -- Value detection local function isTsObject(t) - return type(t)=='table' and t._tsObjectId~=nil + return type(t) == 'table' and t._tsObjectId ~= nil end local function tsIsObject(name) return tsBool(_bllua_ts.call('isObject', name)) end local function tsIsFunction(name) return tsBool(_bllua_ts.call('isFunction', name)) end local function tsIsFunctionNs(ns, name) return tsBool(_bllua_ts.call('isFunction', ns, name)) end local function tsIsFunctionNsname(nsname) - local ns, name = nsname:match('^([^:]+)::([^:]+)$') - if ns then return tsIsFunctionNs(ns, name) - else return tsIsFunction(nsname) end + local ns, name = nsname:match('^([^:]+)::([^:]+)$') + if ns then + return tsIsFunctionNs(ns, name) + else + return tsIsFunction(nsname) + end end function bl.isObject(obj) - if isTsObject(obj) then - obj = obj._tsObjectId - elseif type(obj)=='number' then - obj = tostring(obj) - elseif type(obj)~='string' then - error('bl.isObject: argument #1: expected torque object, number, or string', 2) - end - return tsIsObject(obj) + if isTsObject(obj) then + obj = obj._tsObjectId + elseif type(obj) == 'number' then + obj = tostring(obj) + elseif type(obj) ~= 'string' then + error('bl.isObject: argument #1: expected torque object, number, or string', 2) + end + return tsIsObject(obj) end + function bl.isFunction(a1, a2) - if type(a1)~='string' then - error('bl.isFunction: argument #1: expected string', 2) end - if a2 then - if type(a2)~='string' then - error('bl.isFunction: argument #2: expected string', 2) end - return tsIsFunctionNs(a1, a2) - else - return tsIsFunction(a1) - end + if type(a1) ~= 'string' then + error('bl.isFunction: argument #1: expected string', 2) + end + if a2 then + if type(a2) ~= 'string' then + error('bl.isFunction: argument #2: expected string', 2) + end + return tsIsFunctionNs(a1, a2) + else + return tsIsFunction(a1) + end end -- Torque object pseudo-class local tsClassMeta = { - __tostring = function(t) - return 'torqueClass:'..t._name.. - (t._inherit and (':'..t._inherit._name) or '') - end, + __tostring = function(t) + return 'torqueClass:' .. t._name .. + (t._inherit and (':' .. t._inherit._name) or '') + end, } bl._objectUserMetas = bl._objectUserMetas or {} function bl.class(cname, inhname) - if not ( type(cname)=='string' and isValidFuncName(cname) ) then - error('bl.class: argument #1: invalid class name', 2) end - if not ( inhname==nil or (type(inhname)=='string' and isValidFuncName(inhname)) ) then - error('bl.class: argument #2: inherit name must be a string or nil', 2) end - cname = cname:lower() - - local met = bl._objectUserMetas[cname] or { - _name = cname, - _inherit = nil, - _children = {}, - } - bl._objectUserMetas[cname] = met - setmetatable(met, tsClassMeta) - - if inhname then - inhname = inhname:lower() - - local inh = bl._objectUserMetas[inhname] - if not inh then error('bl.class: argument #2: \''..inhname..'\' is not the '.. - 'name of an existing class', 2) end - - inh._children[cname] = true - - local inhI = met._inherit - if inhI and inhI~=inh then - error('bl.class: argument #2: class already exists and '.. - 'inherits a different parent.', 2) end - met._inherit = inh - - -- apply inherited method and field types - for ftname, typ in pairs(bl._forceType) do - local cname2, rest = classFromForceTypeStr(ftname) - if cname2==inhname then - setForceType(cname..rest, typ) - end - end - end + if not (type(cname) == 'string' and isValidFuncName(cname)) then + error('bl.class: argument #1: invalid class name', 2) + end + if not (inhname == nil or (type(inhname) == 'string' and isValidFuncName(inhname))) then + error('bl.class: argument #2: inherit name must be a string or nil', 2) + end + cname = cname:lower() + + local met = bl._objectUserMetas[cname] or { + _name = cname, + _inherit = nil, + _children = {}, + } + bl._objectUserMetas[cname] = met + setmetatable(met, tsClassMeta) + + if inhname then + inhname = inhname:lower() + + local inh = bl._objectUserMetas[inhname] + if not inh then + error('bl.class: argument #2: \'' .. inhname .. '\' is not the ' .. + 'name of an existing class', 2) + end + + inh._children[cname] = true + + local inhI = met._inherit + if inhI and inhI ~= inh then + error('bl.class: argument #2: class already exists and ' .. + 'inherits a different parent.', 2) + end + met._inherit = inh + + -- apply inherited method and field types + for ftname, typ in pairs(bl._forceType) do + local cname2, rest = classFromForceTypeStr(ftname) + if cname2 == inhname then + setForceType(cname .. rest, typ) + end + end + end end + local function objectInheritedMetas(name) - local inh = bl._objectUserMetas[name:lower()] - return function() - local inhP = inh - if inhP==nil then return nil end - inh = inh._inherit - return inhP - end + local inh = bl._objectUserMetas[name:lower()] + return function() + local inhP = inh + if inhP == nil then return nil end + inh = inh._inherit + return inhP + end end local tsObjectMeta = { - -- __index: Called when accessing fields that don't exist in the object itself - -- Return torque member function or value - __index = function(t, name) - if rawget(t,'_deleted') then - error('ts object index: object no longer exists', 2) end - if type(name)~='string' and type(name)~='number' then - error('ts object index: index must be a string or number', 2) end - if getmetatable(t)[name] then - return getmetatable(t)[name] - elseif type(name)=='number' then - if not tsIsFunctionNs(rawget(t,'_tsNamespace'), 'getObject') then - error('ts object __index: index is number, but object does not have '.. - 'getObject method', 2) end - return toTsObject(_bllua_ts.callobj(t._tsObjectId, 'getObject', - tostring(name))) - else - for inh in objectInheritedMetas(rawget(t,'_tsClassName')) do - if inh[name] then return inh[name] end - end - if - tsIsFunctionNs(rawget(t,'_tsNamespace'), name) or - tsIsFunctionNs(rawget(t,'_tsName'), name) - then - return function(t, ...) - local args = {...} - local argsS = arglistToTs(args) - return valFromTs( - _bllua_ts.callobj(rawget(t,'_tsObjectId'), name, unpack(argsS)), - rawget(t,'_tsName') and rawget(t,'_tsName')..'::'..name, - rawget(t,'_tsNamespace')..'::'..name) - end - else - return valFromTs( - _bllua_ts.getfield(rawget(t,'_tsObjectId'), name), - rawget(t,'_tsName') and rawget(t,'_tsName')..'.'..name, - rawget(t,'_tsNamespace')..'.'..name) - end - end - end, - -- __newindex: Called when setting fields on the object - -- Set lua data - -- Use :set() to set Torque data - __newindex = function(t, name, val) - if rawget(t,'_deleted') then - error('ts object newindex: object no longer exists', 2) end - if type(name)~='string' then - error('ts object newindex: index must be a string', 2) end - rawset(t, name, val) - -- create strong reference since it's now storing lua data - bl._objectsStrong[rawget(t,'_tsObjectId')] = t - end, - -- object:set(fieldName, value) - -- Use to set torque data - set = function(t, name, val) - if t==nil or type(t)~='table' or not t._tsObjectId then - error('ts object method: be sure to use :func() not .func()', 2) end - if t._deleted then - error('ts object method: object no longer exists', 2) end - if type(name)~='string' then - error('ts object :set(): index must be a string', 2) end - _bllua_ts.setfield(t._tsObjectId, name, valToTs(val)) - end, - -- __tostring: Called when printing - -- Display a nice info string - __tostring = function(t) - return 'torque:'..t._tsNamespace..':'..t._tsObjectId.. - (t._tsName~='' and ('('..t._tsName..')') or '') - end, - -- #object - -- If the object has a getCount method, return its count - __len = function(t) - if t._deleted then - error('ts object __len: object no longer exists', 2) end - if not tsIsFunctionNs(t._tsNamespace, 'getCount') then - error('ts object __len: object has no getCount method', 2) end - return tonumber(_bllua_ts.callobj(t._tsObjectId, 'getCount')) - end, - -- object:members() - -- Return an iterator for Torque objects with the getCount and getObject methods - -- for index, object in group:members() do ... end - members = function(t) - if t==nil then - error('ts object method: be sure to use :func() not .func()', 2) end - if t._deleted then - error('ts object method: object no longer exists', 2) end - if not ( - tsIsFunctionNs(t._tsNamespace, 'getCount' ) and - tsIsFunctionNs(t._tsNamespace, 'getObject')) then - error('ts object :members() - '.. - 'Object does not have getCount and getObject methods', 2) end - local count = tonumber(_bllua_ts.callobj(t._tsObjectId, 'getCount')) - local idx = 0 - return function() - if idx < count then - local obj = toTsObject(_bllua_ts.callobj(t._tsObjectId, - 'getObject', tostring(idx))) - idx = idx+1 - return idx-1, obj - else - return nil - end - end - end, - -- Wrap some Torque functions for performance and error checking - getName = function(t) - if t==nil then - error('ts object method: be sure to use :func() not .func()', 2) end - if t._deleted then - error('ts object method: object no longer exists', 2) end - return t._tsName - end, - getId = function(t) - if t==nil then - error('ts object method: be sure to use :func() not .func()', 2) end - if t._deleted then - error('ts object method: object no longer exists', 2) end - return tonumber(t._tsObjectId) - end, - getType = function(t) - if t==nil then - error('ts object method: be sure to use :func() not .func()', 2) end - if t._deleted then - error('ts object method: object no longer exists', 2) end - return tsTypesByNum[_bllua_ts.callobj(t._tsObjectId, 'getType')] - end, - ---- Schedule method for objects - --schedule = function(t, time, cb, ...) - -- if type(t)~='table' or not t._tsObjectId then - -- error('ts object method: be sure to use :func() not .func()', 2) end - -- if t._deleted then - -- error('ts object method: object no longer exists', 2) end - -- if type(time)~='number' then - -- error('ts object schedule: argument #2: time must be a number', 2) end - -- if type(cb)~='function' then - -- error('ts object schedule: argument #3: callback must be a function', 2) end - -- local args = {...} - -- bl.schedule(time, function() - -- if tsBool(__bllua_ts.call('isObject', t._tsObjectId)) then - -- pcall(cb, unpack(args)) - -- end - -- end) - --end, - exists = function(t) - if t==nil then - error('ts object method: be sure to use :func() not .func()', 2) end - if t._deleted then - return false end - return tsIsObject(t._tsObjectId) - end, + -- __index: Called when accessing fields that don't exist in the object itself + -- Return torque member function or value + __index = function(t, name) + if rawget(t, '_deleted') then + error('ts object index: object no longer exists', 2) + end + if type(name) ~= 'string' and type(name) ~= 'number' then + error('ts object index: index must be a string or number', 2) + end + if getmetatable(t)[name] then + return getmetatable(t)[name] + elseif type(name) == 'number' then + if not tsIsFunctionNs(rawget(t, '_tsNamespace'), 'getObject') then + error('ts object __index: index is number, but object does not have ' .. + 'getObject method', 2) + end + return toTsObject(_bllua_ts.callobj(t._tsObjectId, 'getObject', + tostring(name))) + else + for inh in objectInheritedMetas(rawget(t, '_tsClassName')) do + if inh[name] then return inh[name] end + end + if + tsIsFunctionNs(rawget(t, '_tsNamespace'), name) or + tsIsFunctionNs(rawget(t, '_tsName'), name) + then + return function(t, ...) + local args = { ... } + local argsS = arglistToTs(args) + return valFromTs( + _bllua_ts.callobj(rawget(t, '_tsObjectId'), name, unpack(argsS)), + rawget(t, '_tsName') and rawget(t, '_tsName') .. '::' .. name, + rawget(t, '_tsNamespace') .. '::' .. name) + end + else + return valFromTs( + _bllua_ts.getfield(rawget(t, '_tsObjectId'), name), + rawget(t, '_tsName') and rawget(t, '_tsName') .. '.' .. name, + rawget(t, '_tsNamespace') .. '.' .. name) + end + end + end, + -- __newindex: Called when setting fields on the object + -- Set lua data + -- Use :set() to set Torque data + __newindex = function(t, name, val) + if rawget(t, '_deleted') then + error('ts object newindex: object no longer exists', 2) + end + if type(name) ~= 'string' then + error('ts object newindex: index must be a string', 2) + end + rawset(t, name, val) + -- create strong reference since it's now storing lua data + bl._objectsStrong[rawget(t, '_tsObjectId')] = t + end, + -- object:set(fieldName, value) + -- Use to set torque data + set = function(t, name, val) + if t == nil or type(t) ~= 'table' or not t._tsObjectId then + error('ts object method: be sure to use :func() not .func()', 2) + end + if t._deleted then + error('ts object method: object no longer exists', 2) + end + if type(name) ~= 'string' then + error('ts object :set(): index must be a string', 2) + end + _bllua_ts.setfield(t._tsObjectId, name, valToTs(val)) + end, + -- __tostring: Called when printing + -- Display a nice info string + __tostring = function(t) + return 'torque:' .. t._tsNamespace .. ':' .. t._tsObjectId .. + (t._tsName ~= '' and ('(' .. t._tsName .. ')') or '') + end, + -- #object + -- If the object has a getCount method, return its count + __len = function(t) + if t._deleted then + error('ts object __len: object no longer exists', 2) + end + if not tsIsFunctionNs(t._tsNamespace, 'getCount') then + error('ts object __len: object has no getCount method', 2) + end + return tonumber(_bllua_ts.callobj(t._tsObjectId, 'getCount')) + end, + -- object:members() + -- Return an iterator for Torque objects with the getCount and getObject methods + -- for index, object in group:members() do ... end + members = function(t) + if t == nil then + error('ts object method: be sure to use :func() not .func()', 2) + end + if t._deleted then + error('ts object method: object no longer exists', 2) + end + if not ( + tsIsFunctionNs(t._tsNamespace, 'getCount') and + tsIsFunctionNs(t._tsNamespace, 'getObject')) then + error('ts object :members() - ' .. + 'Object does not have getCount and getObject methods', 2) + end + local count = tonumber(_bllua_ts.callobj(t._tsObjectId, 'getCount')) + local idx = 0 + return function() + if idx < count then + local obj = toTsObject(_bllua_ts.callobj(t._tsObjectId, + 'getObject', tostring(idx))) + idx = idx + 1 + return idx - 1, obj + else + return nil + end + end + end, + -- Wrap some Torque functions for performance and error checking + getName = function(t) + if t == nil then + error('ts object method: be sure to use :func() not .func()', 2) + end + if t._deleted then + error('ts object method: object no longer exists', 2) + end + return t._tsName + end, + getId = function(t) + if t == nil then + error('ts object method: be sure to use :func() not .func()', 2) + end + if t._deleted then + error('ts object method: object no longer exists', 2) + end + return tonumber(t._tsObjectId) + end, + getType = function(t) + if t == nil then + error('ts object method: be sure to use :func() not .func()', 2) + end + if t._deleted then + error('ts object method: object no longer exists', 2) + end + return tsTypesByNum[_bllua_ts.callobj(t._tsObjectId, 'getType')] + end, + ---- Schedule method for objects + --schedule = function(t, time, cb, ...) + -- if type(t)~='table' or not t._tsObjectId then + -- error('ts object method: be sure to use :func() not .func()', 2) end + -- if t._deleted then + -- error('ts object method: object no longer exists', 2) end + -- if type(time)~='number' then + -- error('ts object schedule: argument #2: time must be a number', 2) end + -- if type(cb)~='function' then + -- error('ts object schedule: argument #3: callback must be a function', 2) end + -- local args = {...} + -- bl.schedule(time, function() + -- if tsBool(__bllua_ts.call('isObject', t._tsObjectId)) then + -- pcall(cb, unpack(args)) + -- end + -- end) + --end, + exists = function(t) + if t == nil then + error('ts object method: be sure to use :func() not .func()', 2) + end + if t._deleted then + return false + end + return tsIsObject(t._tsObjectId) + end, } -- Weak-values table for caching Torque object references -- Objects in this table can be garbage collected if there are no other refs to them if not bl._objectsWeak then - bl._objectsWeak = {} - setmetatable(bl._objectsWeak, { __mode='v' }) + bl._objectsWeak = {} + setmetatable(bl._objectsWeak, { __mode = 'v' }) end -- Strong table for preserving Torque object references containing lua data -- If an object in this table, it will remain here and in the Weak table until deleted if not bl._objectsStrong then - bl._objectsStrong = {} + bl._objectsStrong = {} end -- Hook object deletion to clean up its lua data -- idS is expected to be the object ID number, NOT the object name function _bllua_objectDeleted(idS) - local obj = bl._objectsWeak[idS] - if obj then - obj._deleted = true - bl._objectsStrong[idS] = nil - bl._objectsWeak[idS] = nil - bl._objectsWeak[obj._tsName:lower()] = nil - end + local obj = bl._objectsWeak[idS] + if obj then + obj._deleted = true + bl._objectsStrong[idS] = nil + bl._objectsWeak[idS] = nil + bl._objectsWeak[obj._tsName:lower()] = nil + end end -- Return a Torque object for the object ID string, or create one if none exists toTsObject = function(idiS) - if type(idiS)~='string' then - error('toTsObject: input must be a string', 2) end - idiS = idiS:lower() - if bl._objectsWeak[idiS] then return bl._objectsWeak[idiS] end - - if not tsBool(_bllua_ts.call('isObject', idiS)) then - --error('toTsObject: object \''..idiS..'\' does not exist', 2) end - return nil end - - local className = _bllua_ts.callobj(idiS, 'getClassName') - local obj = { - _tsObjectId = _bllua_ts.callobj(idiS, 'getId' ), - _tsName = _bllua_ts.callobj(idiS, 'getName' ), - _tsNamespace = className, - _tsClassName = className:lower(), - } - setmetatable(obj, tsObjectMeta) - - bl._objectsWeak[obj._tsObjectId ] = obj - bl._objectsWeak[obj._tsName:lower()] = obj - return obj + if type(idiS) ~= 'string' then + error('toTsObject: input must be a string', 2) + end + idiS = idiS:lower() + if bl._objectsWeak[idiS] then return bl._objectsWeak[idiS] end + + if not tsBool(_bllua_ts.call('isObject', idiS)) then + --error('toTsObject: object \''..idiS..'\' does not exist', 2) end + return nil + end + + local className = _bllua_ts.callobj(idiS, 'getClassName') + local obj = { + _tsObjectId = _bllua_ts.callobj(idiS, 'getId'), + _tsName = _bllua_ts.callobj(idiS, 'getName'), + _tsNamespace = className, + _tsClassName = className:lower(), + } + setmetatable(obj, tsObjectMeta) + + bl._objectsWeak[obj._tsObjectId] = obj + bl._objectsWeak[obj._tsName:lower()] = obj + return obj end -- Allow bl['namespaced::function']() local function safeNamespaceName(name) - return tostring(name:gsub(':', '_')) + return tostring(name:gsub(':', '_')) end local nscallArgStr = '%a,%b,%c,%d,%e,%f,%g,%h' bl._cachedNamespaceCalls = {} local function tsNamespacedCallTfname(name) - local tfname = bl._cachedNamespaceCalls[name] - if not tfname then - tfname = '_bllua_nscall_'..safeNamespaceName(name) - local tfcode = 'function '..tfname..'('..nscallArgStr..'){'.. - name..'('..nscallArgStr..');}' - _bllua_ts.eval(tfcode) - bl._cachedNamespaceCalls[name] = tfname - end - return tfname + local tfname = bl._cachedNamespaceCalls[name] + if not tfname then + tfname = '_bllua_nscall_' .. safeNamespaceName(name) + local tfcode = 'function ' .. tfname .. '(' .. nscallArgStr .. '){' .. + name .. '(' .. nscallArgStr .. ');}' + _bllua_ts.eval(tfcode) + bl._cachedNamespaceCalls[name] = tfname + end + return tfname end local function tsCallGen(name) - return function(...) - local args = {...} - local argsS = arglistToTs(args) - return valFromTs(_bllua_ts.call(name, unpack(argsS)), name) - end + return function(...) + local args = { ... } + local argsS = arglistToTs(args) + return valFromTs(_bllua_ts.call(name, unpack(argsS)), name) + end end -- Metatable for the global bl library -- Allows accessing Torque objects, variables, and functions by indexing it local tsMeta = { - -- __index: Called when accessing fields that don't exist in the table itself - -- Allow indexing by object id: bl[1234] - -- by object name: bl.mainMenuGui - -- by function name: bl.quit() - -- by variable name: bl.iAmAdmin - __index = function(t, name) - if getmetatable(t)[name] then - return getmetatable(t)[name] - elseif type(name)=='string' and bl._objectUserMetas[name:lower()] then - return bl._objectUserMetas[name:lower()] - else - if type(name)=='number' then - return toTsObject(tostring(name)) - elseif name:find('::') then - local ns, rest = name:match('^([^:]+)::(.+)$') - if not ns then error('ts index: invalid name \''..name..'\'', 2) end - if not rest:find('::') and tsIsFunctionNs(ns, rest) then - return tsCallGen(tsNamespacedCallTfname(name)) - else - return valFromTs(_bllua_ts.getvar(name), name) - end - elseif tsIsFunction(name) then - return tsCallGen(name) - elseif tsIsObject(name) then - return toTsObject(name) - else - return valFromTs(_bllua_ts.getvar(name), name) - end - end - end, + -- __index: Called when accessing fields that don't exist in the table itself + -- Allow indexing by object id: bl[1234] + -- by object name: bl.mainMenuGui + -- by function name: bl.quit() + -- by variable name: bl.iAmAdmin + __index = function(t, name) + if getmetatable(t)[name] then + return getmetatable(t)[name] + elseif type(name) == 'string' and bl._objectUserMetas[name:lower()] then + return bl._objectUserMetas[name:lower()] + else + if type(name) == 'number' then + return toTsObject(tostring(name)) + elseif name:find('::') then + local ns, rest = name:match('^([^:]+)::(.+)$') + if not ns then error('ts index: invalid name \'' .. name .. '\'', 2) end + if not rest:find('::') and tsIsFunctionNs(ns, rest) then + return tsCallGen(tsNamespacedCallTfname(name)) + else + return valFromTs(_bllua_ts.getvar(name), name) + end + elseif tsIsFunction(name) then + return tsCallGen(name) + elseif tsIsObject(name) then + return toTsObject(name) + else + return valFromTs(_bllua_ts.getvar(name), name) + end + end + end, } -- bl.set(name, value) -- Used to set global variables function bl.set(name, val) - _bllua_ts.setvar(name, valToTs(val)) + _bllua_ts.setvar(name, valToTs(val)) end -- Utility functions function bl.call(func, ...) - local args = {...} - local argsS = arglistToTs(args) - return _bllua_ts.call(func, unpack(argsS)) + local args = { ... } + local argsS = arglistToTs(args) + return _bllua_ts.call(func, unpack(argsS)) end + function bl.eval(code) - return valFromTs(_bllua_ts.eval(code)) + return valFromTs(_bllua_ts.eval(code)) end + function bl.exec(file) - return valFromTs(_bllua_ts.call('exec', file)) + return valFromTs(_bllua_ts.call('exec', file)) end + function bl.boolean(val) - return val~=nil and - val~=false and - --val~='' and - --val~='0' and - val~=0 + return val ~= nil and + val ~= false and + --val~='' and + --val~='0' and + val ~= 0 end + function bl.object(id) - if type(id)=='table' and id._tsObjectId then - return id - elseif type(id)=='string' or type(id)=='number' then - return toTsObject(tostring(id)) - else - error('bl.object: id must be a ts object, number, or string', 2) - end + if type(id) == 'table' and id._tsObjectId then + return id + elseif type(id) == 'string' or type(id) == 'number' then + return toTsObject(tostring(id)) + else + error('bl.object: id must be a ts object, number, or string', 2) + end end + function bl.array(name, ...) - local rest = {...} - return name..table.concat(rest, '_') + local rest = { ... } + return name .. table.concat(rest, '_') end + function _bllua_call(fnameS, ...) - local args = arglistFromTs('lua:'..fnameS:lower(), {...}) -- todo: allow this though bl.type - if not _G[fnameS] then - error('luacall: no global lua function named \''..fnameS..'\'') end - -- todo: library fields and object methods - local res = _G[fnameS](unpack(args)) - return valToTs(res) + local args = arglistFromTs('lua:' .. fnameS:lower(), { ... }) -- todo: allow this though bl.type + if not _G[fnameS] then + error('luacall: no global lua function named \'' .. fnameS .. '\'') + end + -- todo: library fields and object methods + local res = _G[fnameS](unpack(args)) + return valToTs(res) end -- bl.schedule: Use TS's schedule function to schedule lua calls -- bl.schedule(time, function, args...) -bl._scheduleTable = bl._scheduleTable or {} +bl._scheduleTable = bl._scheduleTable or {} bl._scheduleNextId = bl._scheduleNextId or 1 local function cancelTsSched(sched) - if not (sched and sched.handle) then - error('schedule:cancel() - invalid object', 2) - end - _bllua_ts.call('cancel', sched.handle) - bl._scheduleTable[id] = nil + if not (sched and sched.handle) then + error('schedule:cancel() - invalid object', 2) + end + _bllua_ts.call('cancel', sched.handle) + bl._scheduleTable[id] = nil end function bl.schedule(time, cb, ...) - local id = bl._scheduleNextId - bl._scheduleNextId = bl._scheduleNextId+1 - local args = {...} - local handle = tonumber(_bllua_ts.call('schedule', - time, 0, '_bllua_luacall', '_bllua_schedule_callback', id)) - local sch = { - callback = cb, - args = args, - handle = handle, - cancel = cancelTsSched, - } - bl._scheduleTable[id] = sch - return sch + local id = bl._scheduleNextId + bl._scheduleNextId = bl._scheduleNextId + 1 + local args = { ... } + local handle = tonumber(_bllua_ts.call('schedule', + time, 0, '_bllua_luacall', '_bllua_schedule_callback', id)) + local sch = { + callback = cb, + args = args, + handle = handle, + cancel = cancelTsSched, + } + bl._scheduleTable[id] = sch + return sch end + function _bllua_schedule_callback(idS) - local id = tonumber(idS) or - error('_bllua_schedule_callback: invalid id: '..tostring(idS)) - local sch = bl._scheduleTable[id] - if not sch then error('_bllua_schedule_callback: no schedule with id '..id) end - bl._scheduleTable[id] = nil - sch.callback(unpack(sch.args)) + local id = tonumber(idS) or + error('_bllua_schedule_callback: invalid id: ' .. tostring(idS)) + local sch = bl._scheduleTable[id] + if not sch then error('_bllua_schedule_callback: no schedule with id ' .. id) end + bl._scheduleTable[id] = nil + sch.callback(unpack(sch.args)) end -- serverCmd and clientCmd bl._cmds = bl._cmds or {} function _bllua_process_cmd(cmdS, ...) - local cmd = cmdS:lower() - local args = arglistFromTs(cmd, {...}) - local func = bl._cmds[cmd] - if not func then error('_bllua_process_cmd: no cmd named \''..cmd..'\'') end - func(unpack(args)) --pcall(func, unpack(args)) + local cmd = cmdS:lower() + local args = arglistFromTs(cmd, { ... }) + local func = bl._cmds[cmd] + if not func then error('_bllua_process_cmd: no cmd named \'' .. cmd .. '\'') end + func(unpack(args)) --pcall(func, unpack(args)) end + local function addCmd(cmd, func) - if not isValidFuncName(cmd) then - error('addCmd: invalid function name \''..tostring(cmd)..'\'') end - bl._cmds[cmd] = func - local arglist = '%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o,%p' - _bllua_ts.eval('function '..cmd..'('..arglist..'){'.. - '_bllua_luacall(_bllua_process_cmd,"'..cmd..'",'..arglist..');}') + if not isValidFuncName(cmd) then + error('addCmd: invalid function name \'' .. tostring(cmd) .. '\'') + end + bl._cmds[cmd] = func + local arglist = '%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o,%p' + _bllua_ts.eval('function ' .. cmd .. '(' .. arglist .. '){' .. + '_bllua_luacall(_bllua_process_cmd,"' .. cmd .. '",' .. arglist .. ');}') end function bl.addServerCmd(name, func) - name = name:lower() - addCmd('servercmd'..name, func) - bl._forceType['servercmd'..name..':1'] = 'object' + name = name:lower() + addCmd('servercmd' .. name, func) + bl._forceType['servercmd' .. name .. ':1'] = 'object' end + function bl.addClientCmd(name, func) - name = name:lower() - addCmd('clientcmd'..name, func) + name = name:lower() + addCmd('clientcmd' .. name, func) end -- commandToServer and commandToClient function bl.commandToServer(cmd, ...) - _bllua_ts.call('commandToServer', - _bllua_ts.call('addTaggedString', cmd), - unpack(arglistToTs({...}))) + _bllua_ts.call('commandToServer', + _bllua_ts.call('addTaggedString', cmd), + unpack(arglistToTs({ ... }))) end + function bl.commandToClient(cmd, ...) - _bllua_ts.call('commandToClient', - _bllua_ts.call('addTaggedString', cmd), - unpack(arglistToTs({...}))) + _bllua_ts.call('commandToClient', + _bllua_ts.call('addTaggedString', cmd), + unpack(arglistToTs({ ... }))) end + function bl.commandToAll(cmd, ...) - _bllua_ts.call('commandToAll', - _bllua_ts.call('addTaggedString', cmd), - unpack(arglistToTs({...}))) + _bllua_ts.call('commandToAll', + _bllua_ts.call('addTaggedString', cmd), + unpack(arglistToTs({ ... }))) end -- Hooks (using TS packages) local function isPackageActive(pkg) - local numpkgs = tonumber(_bllua_ts.call('getNumActivePackages')) - for i = 0, numpkgs-1 do - local apkg = _bllua_ts.call('getActivePackage', tostring(i)) - if apkg==pkg then return true end - end - return false + local numpkgs = tonumber(_bllua_ts.call('getNumActivePackages')) + for i = 0, numpkgs - 1 do + local apkg = _bllua_ts.call('getActivePackage', tostring(i)) + if apkg == pkg then return true end + end + return false end local function activatePackage(pkg) - if not isPackageActive(pkg) then - _bllua_ts.call('activatePackage', pkg) - end + if not isPackageActive(pkg) then + _bllua_ts.call('activatePackage', pkg) + end end local function deactivatePackage(pkg) - if isPackageActive(pkg) then - _bllua_ts.call('deactivatePackage', pkg) - end + if isPackageActive(pkg) then + _bllua_ts.call('deactivatePackage', pkg) + end end local hookNargs = 8 local hookArglistLocal = '%a,%b,%c,%d,%e,%f,%g,%h' -local hookArglistGlobal = '$_bllua_hook_arg1,$_bllua_hook_arg2,$_bllua_hook_arg3,$_bllua_hook_arg4,$_bllua_hook_arg5,$_bllua_hook_arg6,$_bllua_hook_arg7,$_bllua_hook_arg8' +local hookArglistGlobal = +'$_bllua_hook_arg1,$_bllua_hook_arg2,$_bllua_hook_arg3,$_bllua_hook_arg4,$_bllua_hook_arg5,$_bllua_hook_arg6,$_bllua_hook_arg7,$_bllua_hook_arg8' bl._hooks = bl._hooks or {} function _bllua_process_hook_before(pkgS, nameS, ...) - local args = arglistFromTs(nameS, {...}) - local func = bl._hooks[pkgS] and bl._hooks[pkgS][nameS] and - bl._hooks[pkgS][nameS].before - if not func then - error('_bllua_process_hook_before: no hook for '..pkgs..':'..nameS) end - _bllua_ts.setvar('_bllua_hook_abort', '0') - func(args) --pcall(func, args) - if args._return then - _bllua_ts.setvar('_bllua_hook_abort', '1') - _bllua_ts.setvar('_bllua_hook_return', valToTs(args._return)) - end - for i=1,hookNargs do - _bllua_ts.setvar('_bllua_hook_arg'..i, valToTs(args[i])) - end + local args = arglistFromTs(nameS, { ... }) + local func = bl._hooks[pkgS] and bl._hooks[pkgS][nameS] and + bl._hooks[pkgS][nameS].before + if not func then + error('_bllua_process_hook_before: no hook for ' .. pkgs .. ':' .. nameS) + end + _bllua_ts.setvar('_bllua_hook_abort', '0') + func(args) --pcall(func, args) + if args._return then + _bllua_ts.setvar('_bllua_hook_abort', '1') + _bllua_ts.setvar('_bllua_hook_return', valToTs(args._return)) + end + for i = 1, hookNargs do + _bllua_ts.setvar('_bllua_hook_arg' .. i, valToTs(args[i])) + end end + function _bllua_process_hook_after(pkgS, nameS, resultS, ...) - nameS = nameS:lower() - local args = arglistFromTs(nameS, {...}) - args._return = valFromTs(resultS, nameS) - local func = bl._hooks[pkgS] and bl._hooks[pkgS][nameS] and - bl._hooks[pkgS][nameS].after - if not func then - error('_bllua_process_hook_after: no hook for '..pkgs..':'..nameS) end - func(args) --pcall(func, args) - return valToTs(args._return) + nameS = nameS:lower() + local args = arglistFromTs(nameS, { ... }) + args._return = valFromTs(resultS, nameS) + local func = bl._hooks[pkgS] and bl._hooks[pkgS][nameS] and + bl._hooks[pkgS][nameS].after + if not func then + error('_bllua_process_hook_after: no hook for ' .. pkgs .. ':' .. nameS) + end + func(args) --pcall(func, args) + return valToTs(args._return) end + local function updateHook(pkg, name, hk) - local beforeCode = hk.before and - ('_bllua_luacall("_bllua_process_hook_before", "'..pkg..'","'..name.. - '",'..hookArglistLocal..');') or '' - local arglist = (hk.before and hookArglistGlobal or hookArglistLocal) - local parentCode = - tsIsFunctionNsname(name) and -- only call parent if it exists - (hk.before and - 'if($_bllua_hook_abort)return $_bllua_hook_return; else ' or '').. - ((hk.after and '%result=' or 'return ').. - 'parent::'..name:match('[^:]+$').. - '('..arglist..');') or '' - local afterCode = hk.after and - ('return _bllua_luacall("_bllua_process_hook_after","'..pkg..'","'..name..'",%result,'.. - arglist..');') or '' - local code = - 'package '..pkg..'{'.. - 'function '..name..'('..hookArglistLocal..'){'.. - beforeCode..parentCode..afterCode.. - '}'.. - '};' - _bllua_ts.eval(code) + local beforeCode = hk.before and + ('_bllua_luacall("_bllua_process_hook_before", "' .. pkg .. '","' .. name .. + '",' .. hookArglistLocal .. ');') or '' + local arglist = (hk.before and hookArglistGlobal or hookArglistLocal) + local parentCode = + tsIsFunctionNsname(name) and -- only call parent if it exists + (hk.before and + 'if($_bllua_hook_abort)return $_bllua_hook_return; else ' or '') .. + ((hk.after and '%result=' or 'return ') .. + 'parent::' .. name:match('[^:]+$') .. + '(' .. arglist .. ');') or '' + local afterCode = hk.after and + ('return _bllua_luacall("_bllua_process_hook_after","' .. pkg .. '","' .. name .. '",%result,' .. + arglist .. ');') or '' + local code = + 'package ' .. pkg .. '{' .. + 'function ' .. name .. '(' .. hookArglistLocal .. '){' .. + beforeCode .. parentCode .. afterCode .. + '}' .. + '};' + _bllua_ts.eval(code) end function bl.hook(pkg, name, time, func) - if not isValidFuncName(pkg) then - error('bl.hook: argument #1: invalid package name \''..tostring(pkg)..'\'', 2) end - if not isValidFuncNameNs(name) then - error('bl.hook: argument #2: invalid function name \''..tostring(name)..'\'', 2) end - if time~='before' and time~='after' then - error('bl.hook: argument #3: time must be \'before\' or \'after\'', 2) end - if type(func)~='function' then - error('bl.hook: argument #4: expected a function', 2) end - - bl._hooks[pkg] = bl._hooks[pkg] or {} - bl._hooks[pkg][name] = bl._hooks[pkg][name] or {} - bl._hooks[pkg][name][time] = func - - updateHook(pkg, name, bl._hooks[pkg][name]) - activatePackage(pkg) + if not isValidFuncName(pkg) then + error('bl.hook: argument #1: invalid package name \'' .. tostring(pkg) .. '\'', 2) + end + if not isValidFuncNameNs(name) then + error('bl.hook: argument #2: invalid function name \'' .. tostring(name) .. '\'', 2) + end + if time ~= 'before' and time ~= 'after' then + error('bl.hook: argument #3: time must be \'before\' or \'after\'', 2) + end + if type(func) ~= 'function' then + error('bl.hook: argument #4: expected a function', 2) + end + + bl._hooks[pkg] = bl._hooks[pkg] or {} + bl._hooks[pkg][name] = bl._hooks[pkg][name] or {} + bl._hooks[pkg][name][time] = func + + updateHook(pkg, name, bl._hooks[pkg][name]) + activatePackage(pkg) end + local function tableEmpty(t) - return next(t)~=nil + return next(t) ~= nil end function bl.unhook(pkg, name, time) - if not isValidFuncName(pkg) then - error('bl.unhook: argument #1: invalid package name \''..tostring(pkg)..'\'', 2) end - if not isValidFuncNameNs(name) then - error('bl.unhook: argument #2: invalid function name \''..tostring(name)..'\'', 2) end - if time~='before' and time~='after' then - error('bl.unhook: argument #3: time must be \'before\' or \'after\'', 2) end - - if not name then - if bl._hooks[pkg] then - for name,hk in pairs(bl._hooks[pkg]) do - updateHook(pkg, name, {}) - end - bl._hooks[pkg] = nil - else - --error('bl.unhook: no hooks registered under package name \''.. - -- pkg..'\'', 2) - end - deactivatePackage(pkg) - else - if bl._hooks[pkg][name] then - if not time then - bl._hooks[pkg][name] = nil - if table.empty(bl._hooks[pkg]) then - bl._hooks[pkg] = nil - deactivatePackage(pkg) - end - updateHook(pkg, name, {}) - else - if time~='before' and time~='after' then - error('bl.unhook: argument #3: time must be nil, \'before\', or \'after\'', 2) end - bl._hooks[pkg][name][time] = nil - if tableEmpty(bl._hooks[pkg][name]) and tableEmpty(bl._hooks[pkg]) then - bl._hooks[pkg] = nil - deactivatePackage(pkg) - updateHook(pkg, name, {}) - else - updateHook(pkg, name, bl._hooks[pkg][name]) - end - end - else - --error('bl.unhook: no hooks registered for function \''..name.. - -- '\' under package name \''..pkg..'\'', 2) - end - end + if not isValidFuncName(pkg) then + error('bl.unhook: argument #1: invalid package name \'' .. tostring(pkg) .. '\'', 2) + end + if not isValidFuncNameNs(name) then + error('bl.unhook: argument #2: invalid function name \'' .. tostring(name) .. '\'', 2) + end + if time ~= 'before' and time ~= 'after' then + error('bl.unhook: argument #3: time must be \'before\' or \'after\'', 2) + end + + if not name then + if bl._hooks[pkg] then + for name, hk in pairs(bl._hooks[pkg]) do + updateHook(pkg, name, {}) + end + bl._hooks[pkg] = nil + else + --error('bl.unhook: no hooks registered under package name \''.. + -- pkg..'\'', 2) + end + deactivatePackage(pkg) + else + if bl._hooks[pkg][name] then + if not time then + bl._hooks[pkg][name] = nil + if table.empty(bl._hooks[pkg]) then + bl._hooks[pkg] = nil + deactivatePackage(pkg) + end + updateHook(pkg, name, {}) + else + if time ~= 'before' and time ~= 'after' then + error('bl.unhook: argument #3: time must be nil, \'before\', or \'after\'', 2) + end + bl._hooks[pkg][name][time] = nil + if tableEmpty(bl._hooks[pkg][name]) and tableEmpty(bl._hooks[pkg]) then + bl._hooks[pkg] = nil + deactivatePackage(pkg) + updateHook(pkg, name, {}) + else + updateHook(pkg, name, bl._hooks[pkg][name]) + end + end + else + --error('bl.unhook: no hooks registered for function \''..name.. + -- '\' under package name \''..pkg..'\'', 2) + end + end end -- Container search/raycast local function vecToTs(v) - if not isTsVector(v) then - error('vecToTs: argument is not a vector', 3) end - return table.concat(v, ' ') + if not isTsVector(v) then + error('vecToTs: argument is not a vector', 3) + end + return table.concat(v, ' ') end local function maskToTs(mask) - if type(mask)=='string' then - local val = tsTypesByName[mask:lower()] - if not val then - error('maskToTs: invalid mask \''..mask..'\'', 3) end - return tostring(val) - elseif type(mask)=='table' then - local tval = 0 - local seen = {} - for i,v in ipairs(mask) do - if not seen[v] then - local val = tsTypesByName[v:lower()] - if not val then - error('maskToTs: invalid mask \''..v.. - '\' at index '..i..' in mask list', 3) end - tval = tval + val - seen[v] = true - end - end - return tostring(tval) - else - error('maskToTs: mask must be a string or table', 3) - end + if type(mask) == 'string' then + local val = tsTypesByName[mask:lower()] + if not val then + error('maskToTs: invalid mask \'' .. mask .. '\'', 3) + end + return tostring(val) + elseif type(mask) == 'table' then + local tval = 0 + local seen = {} + for i, v in ipairs(mask) do + if not seen[v] then + local val = tsTypesByName[v:lower()] + if not val then + error('maskToTs: invalid mask \'' .. v .. + '\' at index ' .. i .. ' in mask list', 3) + end + tval = tval + val + seen[v] = true + end + end + return tostring(tval) + else + error('maskToTs: mask must be a string or table', 3) + end end local function objToTs(obj) - if type(obj)=='number' or type(obj)=='string' then - return tostring(obj) - elseif type(obj)=='table' and obj._tsObjectId then - return tostring(obj._tsObjectId) - else - error('objToTs: invalid object \''..tostring(obj)..'\'', 3) - end + if type(obj) == 'number' or type(obj) == 'string' then + return tostring(obj) + elseif type(obj) == 'table' and obj._tsObjectId then + return tostring(obj._tsObjectId) + else + error('objToTs: invalid object \'' .. tostring(obj) .. '\'', 3) + end end function bl.raycast(start, stop, mask, ignores) - local startS = vecToTs(start) - local stopS = vecToTs(start) - local maskS = maskToTs(mask) - local ignoresS = {} - for _,v in ipairs(ignores) do - table.insert(ignoresS, objToTs(v)) - end - - local retS = _bllua_ts.call('containerRaycast', startS, stopS, maskS, unpack(ignoresS)) - - if retS=='0' then - return nil - else - local hitS, pxS,pyS,pzS, nxS,nyS,nzS = retS:match('^([0-9]+) '.. - '(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+) '.. - '(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+)$') - local hit = toTsObject(hitS) - local pos = vector{tonumber(pxS),tonumber(pyS),tonumber(pzS)} - local norm = vector{tonumber(nxS),tonumber(nyS),tonumber(nzS)} - return hit, pos, norm - end + local startS = vecToTs(start) + local stopS = vecToTs(start) + local maskS = maskToTs(mask) + local ignoresS = {} + for _, v in ipairs(ignores) do + table.insert(ignoresS, objToTs(v)) + end + + local retS = _bllua_ts.call('containerRaycast', startS, stopS, maskS, unpack(ignoresS)) + + if retS == '0' then + return nil + else + local hitS, pxS, pyS, pzS, nxS, nyS, nzS = retS:match('^([0-9]+) ' .. + '(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+) ' .. + '(%-?[0-9%.e]+) (%-?[0-9%.e]+) (%-?[0-9%.e]+)$') + local hit = toTsObject(hitS) + local pos = vector { tonumber(pxS), tonumber(pyS), tonumber(pzS) } + local norm = vector { tonumber(nxS), tonumber(nyS), tonumber(nzS) } + return hit, pos, norm + end end + local function tsContainerSearchIterator() - local retS = _bllua_ts.call('containerSearchNext') - if retS=='0' then - return nil - else - return toTsObject(retS) - end + local retS = _bllua_ts.call('containerSearchNext') + if retS == '0' then + return nil + else + return toTsObject(retS) + end end function bl.boxSearch(pos, size, mask) - local posS = vecToTs(pos) - local sizeS = vecToTs(size) - local maskS = maskToTs(mask) - - _bllua_ts.call('initContainerBoxSearch', posS, sizeS, maskS) - return tsContainerSearchIterator + local posS = vecToTs(pos) + local sizeS = vecToTs(size) + local maskS = maskToTs(mask) + + _bllua_ts.call('initContainerBoxSearch', posS, sizeS, maskS) + return tsContainerSearchIterator end + function bl.radiusSearch(pos, radius, mask) - local posS = vecToTs(pos) - if type(radius)~='number' then - error('bl.radiusSearch: argument #2: radius must be a number', 2) end - local radiusS = tostring(radius) - local maskS = maskToTs(mask) - - _bllua_ts.call('initContainerRadiusSearch', posS, radiusS, maskS) - return tsContainerSearchIterator + local posS = vecToTs(pos) + if type(radius) ~= 'number' then + error('bl.radiusSearch: argument #2: radius must be a number', 2) + end + local radiusS = tostring(radius) + local maskS = maskToTs(mask) + + _bllua_ts.call('initContainerRadiusSearch', posS, radiusS, maskS) + return tsContainerSearchIterator end -- Print/Talk/Echo local maxTsArgLen = 8192 local function valsToString(vals) - local strs = {} - for i,v in ipairs(vals) do - local tstr = table.tostring(v) - if #tstr>maxTsArgLen then - tstr = tostring(v) - end - strs[i] = tstr - end - return table.concat(strs, ' ') + local strs = {} + for i, v in ipairs(vals) do + local tstr = table.tostring(v) + if #tstr > maxTsArgLen then + tstr = tostring(v) + end + strs[i] = tstr + end + return table.concat(strs, ' ') end bl.echo = function(...) - local str = valsToString({...}) - _bllua_ts.call('echo', str) + local str = valsToString({ ... }) + _bllua_ts.call('echo', str) end print = bl.echo bl.talk = function(...) - local str = valsToString({...}) - _bllua_ts.call('echo', str) - _bllua_ts.call('talk', str) + local str = valsToString({ ... }) + _bllua_ts.call('echo', str) + _bllua_ts.call('talk', str) end -- bl.new and bl.datablock local function createTsObj(keyword, class, name, inherit, props) - local propsT = {} - if props then - for k,v in pairs(props) do - if not isValidFuncName(k) then - error('bl.new/bl.datablock: invalid property name \''..k..'\'') end - table.insert(propsT, k..'="'..valToTs(v)..'";') - end - end - - local objS = _bllua_ts.eval( - 'return '..keyword..' '..class..'('.. - (name or '')..(inherit and (':'..inherit) or '')..'){'.. - table.concat(propsT)..'};') - local obj = toTsObject(objS) - if not obj then - error('bl.new/bl.datablock: failed to create object', 3) end - - return obj + local propsT = {} + if props then + for k, v in pairs(props) do + if not isValidFuncName(k) then + error('bl.new/bl.datablock: invalid property name \'' .. k .. '\'') + end + table.insert(propsT, k .. '="' .. valToTs(v) .. '";') + end + end + + local objS = _bllua_ts.eval( + 'return ' .. keyword .. ' ' .. class .. '(' .. + (name or '') .. (inherit and (':' .. inherit) or '') .. '){' .. + table.concat(propsT) .. '};') + local obj = toTsObject(objS) + if not obj then + error('bl.new/bl.datablock: failed to create object', 3) + end + + return obj end local function parseTsDecl(decl) - local class, name, inherit - if decl:find(' ') then -- class ... - local cl, rest = decl:match('^([^ ]+) ([^ ]+)$') - class = cl - if rest:find(':') then -- class name:inherit - name, inherit = rest:match('^([^:]*):([^:]+)$') - if not name then class = nil end -- error - if name=='' then name = nil end -- class :inherit - else - name = rest - end - else -- class - class = decl - end - if not ( - isValidFuncName(class) and - (name==nil or isValidFuncName(name)) and - (inherit==nil or isValidFuncName(inherit)) ) then - error('bl.new/bl.datablock: invalid decl \''..decl..'\'\n'.. - 'must be of the format: \'className\', \'className name\', '.. - '\'className :inherit\', or \'className name:inherit\'', 3) end - return class, name, inherit + local class, name, inherit + if decl:find(' ') then -- class ... + local cl, rest = decl:match('^([^ ]+) ([^ ]+)$') + class = cl + if rest:find(':') then -- class name:inherit + name, inherit = rest:match('^([^:]*):([^:]+)$') + if not name then class = nil end -- error + if name == '' then name = nil end -- class :inherit + else + name = rest + end + else -- class + class = decl + end + if not ( + isValidFuncName(class) and + (name == nil or isValidFuncName(name)) and + (inherit == nil or isValidFuncName(inherit))) then + error('bl.new/bl.datablock: invalid decl \'' .. decl .. '\'\n' .. + 'must be of the format: \'className\', \'className name\', ' .. + '\'className :inherit\', or \'className name:inherit\'', 3) + end + return class, name, inherit end function bl.new(decl, props) - local class, name, inherit = parseTsDecl(decl) - return createTsObj('new', class, name, inherit, props) + local class, name, inherit = parseTsDecl(decl) + return createTsObj('new', class, name, inherit, props) end + function bl.datablock(decl, props) - local class, name, inherit = parseTsDecl(decl) - if not name then error('bl.datablock: must specify a name', 2) end - return createTsObj('datablock', class, name, inherit, props) + local class, name, inherit = parseTsDecl(decl) + if not name then error('bl.datablock: must specify a name', 2) end + return createTsObj('datablock', class, name, inherit, props) end setmetatable(bl, tsMeta)