1
0
forked from redo/BlockLua
This commit is contained in:
2025-10-05 19:50:29 -04:00
parent f447c039c7
commit 01f216f31e
16 changed files with 2824 additions and 2596 deletions

View File

@@ -1,10 +1,12 @@
-- Sanitize the Lua environment to:
-- Prevent scripts from accessing files outside the game directory
-- Prevent usage of libraries other than
-- Prevent usage of libraries other than
-- Utility: Convert a list of strings into a map of string->true
local function tmap(t) local u = {}; for _, n in ipairs(t) do u[n] = true end; return u; end
local function tmap(t)
local u = {}; for _, n in ipairs(t) do u[n] = true end; return u;
end
-- Save banned global variables for wrapping with safe functions
local old_io = io
@@ -15,98 +17,99 @@ local old_package = package
-- Remove all global variables except a whitelist
local ok_names = tmap {
'_G', '_bllua_ts', '_bllua_on_unload', '_bllua_on_error',
'string', 'table', 'math', 'coroutine', 'bit',
'pairs', 'ipairs', 'next', 'unpack', 'select',
'error', 'assert', 'pcall', 'xpcall',
'type', 'tostring', 'tonumber',
'loadstring',
'getmetatable', 'setmetatable',
'rawget', 'rawset', 'rawequal', 'rawlen',
'module', '_VERSION',
'_G', '_bllua_ts', '_bllua_on_unload', '_bllua_on_error',
'string', 'table', 'math', 'coroutine', 'bit',
'pairs', 'ipairs', 'next', 'unpack', 'select',
'error', 'assert', 'pcall', 'xpcall',
'type', 'tostring', 'tonumber',
'loadstring',
'getmetatable', 'setmetatable',
'rawget', 'rawset', 'rawequal', 'rawlen',
'module', '_VERSION',
}
local not_ok_names = {}
for n, _ in pairs(_G) do
if not ok_names[n] then
table.insert(not_ok_names, n)
end
if not ok_names[n] then
table.insert(not_ok_names, n)
end
end
for _, n in ipairs(not_ok_names) do
_G[n] = nil
_G[n] = nil
end
-- Sanitize file paths to point only to allowed files within the game directory
-- List of allowed directories for reading/writing
local allowed_dirs = tmap {
'add-ons', 'base', 'config', 'saves', 'screenshots', 'shaders'
'add-ons', 'base', 'config', 'saves', 'screenshots', 'shaders'
}
-- List of allowed directories for reading only
local allowed_dirs_readonly = tmap {
'lualib'
'lualib'
}
-- List of disallowed file extensions - basically executable file extensions
-- Note that even without this protection, exploiting would still require somehow
-- getting a file within the allowed directories to autorun,
-- so this is just a precaution.
local disallowed_exts = tmap {
-- windows
'bat','bin','cab','cmd','com','cpl','ex_','exe','gadget','inf','ins','inx','isu',
'job','jse','lnk','msc','msi','msp','mst','paf','pif','ps1','reg','rgs','scr',
'sct','shb','shs','u3p','vb','vbe','vbs','vbscript','ws','wsf','wsh',
-- linux
'csh','ksh','out','run','sh',
-- mac/other
'action','apk','app','command','ipa','osx','prg','workflow',
-- windows
'bat', 'bin', 'cab', 'cmd', 'com', 'cpl', 'ex_', 'exe', 'gadget', 'inf', 'ins', 'inx', 'isu',
'job', 'jse', 'lnk', 'msc', 'msi', 'msp', 'mst', 'paf', 'pif', 'ps1', 'reg', 'rgs', 'scr',
'sct', 'shb', 'shs', 'u3p', 'vb', 'vbe', 'vbs', 'vbscript', 'ws', 'wsf', 'wsh',
-- linux
'csh', 'ksh', 'out', 'run', 'sh',
-- mac/other
'action', 'apk', 'app', 'command', 'ipa', 'osx', 'prg', 'workflow',
}
-- Arguments: file name (relative to game directory), boolean true if only reading
-- Return: clean file path if allowed (or nil if disallowed),
-- error string (or nil if allowed)
local function safe_path(fn, readonly)
fn = fn:gsub('\\', '/')
fn = fn:gsub('^ +', '')
fn = fn:gsub(' +$', '')
-- whitelist characters
local ic = fn:find('[^a-zA-Z0-9_%-/ %.]')
if ic then
return nil, 'Filename \''..fn..'\' contains invalid character \''..
fn:sub(ic, ic)..'\' at position '..ic
end
-- disallow up-dirs, absolute paths, and relative paths
-- './' and '../' are possible in scripts, because they're processed into
-- absolute paths in util.lua before reaching here
if fn:find('^%.') or fn:find('%.%.') or fn:find(':') or fn:find('^/') then
return nil, 'Filename \''..fn..'\' contains invalid sequence'
end
-- allow only whitelisted dirs
local dir = fn:match('^([^/]+)/')
if (not dir) or (
(not allowed_dirs[dir:lower()]) and
((not readonly) or (not allowed_dirs_readonly[dir:lower()])) ) then
return nil, 'filename is in disallowed directory '..(dir or 'nil')
end
-- disallow blacklisted extensions or no extension
local ext = fn:match('%.([^/%.]+)$')
if (not ext) or (disallowed_exts[ext:lower()]) then
return nil, 'Filename \''..fn..'\' has disallowed extension \''..
(ext or '')..'\''
end
return fn, nil
fn = fn:gsub('\\', '/')
fn = fn:gsub('^ +', '')
fn = fn:gsub(' +$', '')
-- whitelist characters
local ic = fn:find('[^a-zA-Z0-9_%-/ %.]')
if ic then
return nil, 'Filename \'' .. fn .. '\' contains invalid character \'' ..
fn:sub(ic, ic) .. '\' at position ' .. ic
end
-- disallow up-dirs, absolute paths, and relative paths
-- './' and '../' are possible in scripts, because they're processed into
-- absolute paths in util.lua before reaching here
if fn:find('^%.') or fn:find('%.%.') or fn:find(':') or fn:find('^/') then
return nil, 'Filename \'' .. fn .. '\' contains invalid sequence'
end
-- allow only whitelisted dirs
local dir = fn:match('^([^/]+)/')
if (not dir) or (
(not allowed_dirs[dir:lower()]) and
((not readonly) or (not allowed_dirs_readonly[dir:lower()]))) then
return nil, 'filename is in disallowed directory ' .. (dir or 'nil')
end
-- disallow blacklisted extensions or no extension
local ext = fn:match('%.([^/%.]+)$')
if (not ext) or (disallowed_exts[ext:lower()]) then
return nil, 'Filename \'' .. fn .. '\' has disallowed extension \'' ..
(ext or '') .. '\''
end
return fn, nil
end
-- Wrap io.open with path sanitization
function _bllua_io_open(fn, md)
md = md or 'r'
local readonly = md=='r' or md=='rb'
local fns, err = safe_path(fn, readonly)
if fns then
return old_io.open(fns, md)
else
return nil, err
end
md = md or 'r'
local readonly = md == 'r' or md == 'rb'
local fns, err = safe_path(fn, readonly)
if fns then
return old_io.open(fns, md)
else
return nil, err
end
end
-- Allow io.type (works on file handles returned by io.open)
function _bllua_io_type(f)
return old_io.type(f)
return old_io.type(f)
end
-- Wrap require with a blacklist for unsafe built-in modules
@@ -114,29 +117,30 @@ end
-- Note that util.lua wraps this and provides 'require',
-- only falling back here if the package is not found in user files
local disallowed_packages = tmap {
'ffi', 'debug', 'package', 'io', 'os',
'_bllua_ts',
'ffi', 'debug', 'package', 'io', 'os',
'_bllua_ts',
}
function _bllua_requiresecure(name)
if name:find('[^a-zA-Z0-9_%-%.]') or name:find('%.%.') or
name:find('^%.') or name:find('%.$') then
error('require: package name contains invalid character', 3)
elseif disallowed_packages[name] then
error('require: attempt to require disallowed module \''..name..'\'', 3)
else
-- todo: reimplement require to not use package.* stuff?
return old_require(name)
end
if name:find('[^a-zA-Z0-9_%-%.]') or name:find('%.%.') or
name:find('^%.') or name:find('%.$') then
error('require: package name contains invalid character', 3)
elseif disallowed_packages[name] then
error('require: attempt to require disallowed module \'' .. name .. '\'', 3)
else
-- todo: reimplement require to not use package.* stuff?
return old_require(name)
end
end
package = {
seeall = old_package.seeall,
seeall = old_package.seeall,
}
-- Provide limited debug
debug = {
traceback = old_debug.traceback,
getinfo = old_debug.getinfo,
getfilename = old_debug.getfilename, -- defined in lua.env.lua
traceback = old_debug.traceback,
getinfo = old_debug.getinfo,
getfilename = old_debug.getfilename, -- defined in lua.env.lua
}
_bllua_ts.echo(' Executed bllua-env-safe.lua')

View File

@@ -9,32 +9,32 @@ _bllua_on_unload = {}
-- Utility for getting the current filename
function debug.getfilename(level)
if type(level) == 'number' then level = level+1 end
local info = debug.getinfo(level)
if not info then return nil end
local filename = info.source:match('^%-%-%[%[([^%]]+)%]%]')
return filename
if type(level) == 'number' then level = level + 1 end
local info = debug.getinfo(level)
if not info then return nil end
local filename = info.source:match('^%-%-%[%[([^%]]+)%]%]')
return filename
end
-- Called when pcall fails on a ts->lua call, used to print detailed error info
function _bllua_on_error(err)
err = err:match(': (.+)$') or err
local tracelines = {err}
local level = 2
while true do
local info = debug.getinfo(level)
if not info then break end
local filename = debug.getfilename(level) or info.short_src
local funcname = info.name
if funcname=='dofile' then break end
table.insert(tracelines, string.format('%s:%s in function \'%s\'',
filename,
info.currentline==-1 and '' or info.currentline..':',
funcname
))
level = level+1
end
return table.concat(tracelines, '\n')
err = err:match(': (.+)$') or err
local tracelines = { err }
local level = 2
while true do
local info = debug.getinfo(level)
if not info then break end
local filename = debug.getfilename(level) or info.short_src
local funcname = info.name
if funcname == 'dofile' then break end
table.insert(tracelines, string.format('%s:%s in function \'%s\'',
filename,
info.currentline == -1 and '' or info.currentline .. ':',
funcname
))
level = level + 1
end
return table.concat(tracelines, '\n')
end
_bllua_ts.echo(' Executed bllua-env.lua')

View File

@@ -4,129 +4,129 @@
-- Class hierarchy, adapted from https://notabug.org/Queuenard/blockland-DLL-tools/src/master/class_hierarchy
bl.class('SimObject')
bl.class('ScriptObject', 'SimObject')
bl.class('SimSet', 'SimObject')
bl.class('SimGroup', 'SimSet')
bl.class('GuiControl', 'SimGroup')
bl.class('GuiTextCtrl' , 'GuiControl')
bl.class('GuiSwatchCtrl' , 'GuiControl')
bl.class('GuiButtonBaseCtrl' , 'GuiControl')
bl.class('GuiArrayCtrl' , 'GuiControl')
bl.class('GuiScrollCtrl' , 'GuiControl')
bl.class('GuiMouseEventCtrl' , 'GuiControl')
bl.class('GuiProgressCtrl' , 'GuiControl')
bl.class('GuiSliderCtrl' , 'GuiControl')
bl.class('GuiConsoleTextCtrl' , 'GuiControl')
bl.class('GuiTSCtrl' , 'GuiControl')
bl.class('GuiObjectView', 'GuiTSCtrl')
bl.class('GameTSCtrl' , 'GuiTSCtrl')
bl.class('EditTSCtrl' , 'GuiTSCtrl')
bl.class('GuiPlayerView', 'GuiTSCtrl')
bl.class('GuiShapeNameHud' , 'GuiControl')
bl.class('GuiHealthBarHud' , 'GuiControl')
bl.class('GuiGraphCtrl' , 'GuiControl')
bl.class('GuiInspector' , 'GuiControl')
bl.class('GuiChunkedBitmapCtrl', 'GuiControl')
bl.class('GuiInputCtrl' , 'GuiControl')
bl.class('GuiNoMouseCtrl' , 'GuiControl')
bl.class('GuiBitmapBorderCtrl' , 'GuiControl')
bl.class('GuiBackgroundCtrl' , 'GuiControl')
bl.class('GuiEditorRuler' , 'GuiControl')
bl.class('GuiClockHud' , 'GuiControl')
bl.class('GuiEditCtrl' , 'GuiControl')
bl.class('GuiFilterCtrl' , 'GuiControl')
bl.class('GuiFrameSetCtrl' , 'GuiControl')
bl.class('GuiMenuBar' , 'GuiControl')
bl.class('GuiMessageVectorCtrl', 'GuiControl')
bl.class('GuiBitmapCtrl' , 'GuiControl')
bl.class('GuiCrossHairHud', 'GuiBitmapCtrl')
bl.class('ScriptGroup', 'SimGroup')
bl.class('NetConnection', 'SimGroup')
bl.class('GameConnection', 'NetConnection')
bl.class('Path', 'SimGroup')
bl.class('TCPObject', 'SimObject')
bl.class('SOCKObject', 'TCPObject')
bl.class('HTTPObject', 'TCPObject')
bl.class('SimDataBlock', 'SimObject')
bl.class('AudioEnvironment' , 'SimDataBlock')
bl.class('AudioSampleEnvironment', 'SimDataBlock')
bl.class('AudioDescription' , 'SimDataBlock')
bl.class('GameBaseData' , 'SimDataBlock')
bl.class('ShapeBaseData' , 'GameBaseData')
bl.class('CameraData' , 'ShapeBaseData')
bl.class('ItemData' , 'ShapeBaseData')
bl.class('MissionMarkerData', 'ShapeBaseData')
bl.class('PathCameraData' , 'ShapeBaseData')
bl.class('PlayerData' , 'ShapeBaseData')
bl.class('StaticShapeData' , 'ShapeBaseData')
bl.class('VehicleData' , 'ShapeBaseData')
bl.class('FlyingVehicleData' , 'VehicleData')
bl.class('WheeledVehicleData', 'VehicleData')
bl.class('DebrisData' , 'GameBaseData')
bl.class('ProjectileData' , 'GameBaseData')
bl.class('ShapeBaseImageData' , 'GameBaseData')
bl.class('TriggerData' , 'GameBaseData')
bl.class('ExplosionData' , 'GameBaseData')
bl.class('fxLightData' , 'GameBaseData')
bl.class('LightningData' , 'GameBaseData')
bl.class('ParticleEmitterNodeData', 'GameBaseData')
bl.class('SplashData' , 'GameBaseData')
bl.class('fxDTSBrickData' , 'GameBaseData')
bl.class('ParticleEmitterData' , 'GameBaseData')
bl.class('WheeledVehicleTire' , 'SimDataBlock')
bl.class('WheeledVehicleSpring' , 'SimDataBlock')
bl.class('TSShapeConstructor' , 'SimDataBlock')
bl.class('AudioProfile' , 'SimDataBlock')
bl.class('ParticleData' , 'SimDataBlock')
bl.class('MaterialPropertyMap', 'SimObject')
bl.class('NetObject', 'SimObject')
bl.class('SceneObject', 'NetObject')
bl.class('GameBase', 'SceneObject')
bl.class('ShapeBase', 'GameBase')
bl.class('MissionMarker', 'ShapeBase')
bl.class('SpawnSphere' , 'MissionMarker')
bl.class('VehicleSpawnMarker', 'MissionMarker')
bl.class('Waypoint' , 'MissionMarker')
bl.class('StaticShape' , 'ShapeBase')
bl.class('ScopeAlwaysShape', 'StaticShape')
bl.class('Player' , 'ShapeBase')
bl.class('AIPlayer', 'Player')
bl.class('Camera' , 'ShapeBase')
bl.class('Item' , 'ShapeBase')
bl.class('PathCamera' , 'ShapeBase')
bl.class('Vehicle' , 'ShapeBase')
bl.class('FlyingVehicle' , 'Vehicle')
bl.class('WheeledVehicle', 'Vehicle')
bl.class('Explosion' , 'GameBase')
bl.class('Splash' , 'GameBase')
bl.class('Debris' , 'GameBase')
bl.class('Projectile' , 'GameBase')
bl.class('Trigger' , 'GameBase')
bl.class('fxLight' , 'GameBase')
bl.class('Lightning' , 'GameBase')
bl.class('ParticleEmitterNode', 'GameBase')
bl.class('ParticleEmitter' , 'GameBase')
bl.class('Precipitation' , 'GameBase')
bl.class('TSStatic' , 'SceneObject')
bl.class('VehicleBlocker', 'SceneObject')
bl.class('Marker' , 'SceneObject')
bl.class('AudioEmitter' , 'SceneObject')
bl.class('PhysicalZone' , 'SceneObject')
bl.class('fxDayCycle' , 'SceneObject')
bl.class('fxDTSBrick' , 'SceneObject')
bl.class('fxPlane' , 'SceneObject')
bl.class('fxSunLight' , 'SceneObject')
bl.class('Sky' , 'SceneObject')
bl.class('SceneRoot' , 'SceneObject')
bl.class('Sun', 'NetObject')
bl.class('GuiCursor', 'SimObject')
bl.class('ConsoleLogger' , 'SimObject')
bl.class('QuotaObject' , 'SimObject')
bl.class('FileObject' , 'SimObject')
bl.class('BanList' , 'SimObject')
bl.class('GuiControlProfile', 'SimObject')
bl.class('MessageVector' , 'SimObject')
bl.class('ActionMap' , 'SimObject')
bl.class('ScriptObject', 'SimObject')
bl.class('SimSet', 'SimObject')
bl.class('SimGroup', 'SimSet')
bl.class('GuiControl', 'SimGroup')
bl.class('GuiTextCtrl', 'GuiControl')
bl.class('GuiSwatchCtrl', 'GuiControl')
bl.class('GuiButtonBaseCtrl', 'GuiControl')
bl.class('GuiArrayCtrl', 'GuiControl')
bl.class('GuiScrollCtrl', 'GuiControl')
bl.class('GuiMouseEventCtrl', 'GuiControl')
bl.class('GuiProgressCtrl', 'GuiControl')
bl.class('GuiSliderCtrl', 'GuiControl')
bl.class('GuiConsoleTextCtrl', 'GuiControl')
bl.class('GuiTSCtrl', 'GuiControl')
bl.class('GuiObjectView', 'GuiTSCtrl')
bl.class('GameTSCtrl', 'GuiTSCtrl')
bl.class('EditTSCtrl', 'GuiTSCtrl')
bl.class('GuiPlayerView', 'GuiTSCtrl')
bl.class('GuiShapeNameHud', 'GuiControl')
bl.class('GuiHealthBarHud', 'GuiControl')
bl.class('GuiGraphCtrl', 'GuiControl')
bl.class('GuiInspector', 'GuiControl')
bl.class('GuiChunkedBitmapCtrl', 'GuiControl')
bl.class('GuiInputCtrl', 'GuiControl')
bl.class('GuiNoMouseCtrl', 'GuiControl')
bl.class('GuiBitmapBorderCtrl', 'GuiControl')
bl.class('GuiBackgroundCtrl', 'GuiControl')
bl.class('GuiEditorRuler', 'GuiControl')
bl.class('GuiClockHud', 'GuiControl')
bl.class('GuiEditCtrl', 'GuiControl')
bl.class('GuiFilterCtrl', 'GuiControl')
bl.class('GuiFrameSetCtrl', 'GuiControl')
bl.class('GuiMenuBar', 'GuiControl')
bl.class('GuiMessageVectorCtrl', 'GuiControl')
bl.class('GuiBitmapCtrl', 'GuiControl')
bl.class('GuiCrossHairHud', 'GuiBitmapCtrl')
bl.class('ScriptGroup', 'SimGroup')
bl.class('NetConnection', 'SimGroup')
bl.class('GameConnection', 'NetConnection')
bl.class('Path', 'SimGroup')
bl.class('TCPObject', 'SimObject')
bl.class('SOCKObject', 'TCPObject')
bl.class('HTTPObject', 'TCPObject')
bl.class('SimDataBlock', 'SimObject')
bl.class('AudioEnvironment', 'SimDataBlock')
bl.class('AudioSampleEnvironment', 'SimDataBlock')
bl.class('AudioDescription', 'SimDataBlock')
bl.class('GameBaseData', 'SimDataBlock')
bl.class('ShapeBaseData', 'GameBaseData')
bl.class('CameraData', 'ShapeBaseData')
bl.class('ItemData', 'ShapeBaseData')
bl.class('MissionMarkerData', 'ShapeBaseData')
bl.class('PathCameraData', 'ShapeBaseData')
bl.class('PlayerData', 'ShapeBaseData')
bl.class('StaticShapeData', 'ShapeBaseData')
bl.class('VehicleData', 'ShapeBaseData')
bl.class('FlyingVehicleData', 'VehicleData')
bl.class('WheeledVehicleData', 'VehicleData')
bl.class('DebrisData', 'GameBaseData')
bl.class('ProjectileData', 'GameBaseData')
bl.class('ShapeBaseImageData', 'GameBaseData')
bl.class('TriggerData', 'GameBaseData')
bl.class('ExplosionData', 'GameBaseData')
bl.class('fxLightData', 'GameBaseData')
bl.class('LightningData', 'GameBaseData')
bl.class('ParticleEmitterNodeData', 'GameBaseData')
bl.class('SplashData', 'GameBaseData')
bl.class('fxDTSBrickData', 'GameBaseData')
bl.class('ParticleEmitterData', 'GameBaseData')
bl.class('WheeledVehicleTire', 'SimDataBlock')
bl.class('WheeledVehicleSpring', 'SimDataBlock')
bl.class('TSShapeConstructor', 'SimDataBlock')
bl.class('AudioProfile', 'SimDataBlock')
bl.class('ParticleData', 'SimDataBlock')
bl.class('MaterialPropertyMap', 'SimObject')
bl.class('NetObject', 'SimObject')
bl.class('SceneObject', 'NetObject')
bl.class('GameBase', 'SceneObject')
bl.class('ShapeBase', 'GameBase')
bl.class('MissionMarker', 'ShapeBase')
bl.class('SpawnSphere', 'MissionMarker')
bl.class('VehicleSpawnMarker', 'MissionMarker')
bl.class('Waypoint', 'MissionMarker')
bl.class('StaticShape', 'ShapeBase')
bl.class('ScopeAlwaysShape', 'StaticShape')
bl.class('Player', 'ShapeBase')
bl.class('AIPlayer', 'Player')
bl.class('Camera', 'ShapeBase')
bl.class('Item', 'ShapeBase')
bl.class('PathCamera', 'ShapeBase')
bl.class('Vehicle', 'ShapeBase')
bl.class('FlyingVehicle', 'Vehicle')
bl.class('WheeledVehicle', 'Vehicle')
bl.class('Explosion', 'GameBase')
bl.class('Splash', 'GameBase')
bl.class('Debris', 'GameBase')
bl.class('Projectile', 'GameBase')
bl.class('Trigger', 'GameBase')
bl.class('fxLight', 'GameBase')
bl.class('Lightning', 'GameBase')
bl.class('ParticleEmitterNode', 'GameBase')
bl.class('ParticleEmitter', 'GameBase')
bl.class('Precipitation', 'GameBase')
bl.class('TSStatic', 'SceneObject')
bl.class('VehicleBlocker', 'SceneObject')
bl.class('Marker', 'SceneObject')
bl.class('AudioEmitter', 'SceneObject')
bl.class('PhysicalZone', 'SceneObject')
bl.class('fxDayCycle', 'SceneObject')
bl.class('fxDTSBrick', 'SceneObject')
bl.class('fxPlane', 'SceneObject')
bl.class('fxSunLight', 'SceneObject')
bl.class('Sky', 'SceneObject')
bl.class('SceneRoot', 'SceneObject')
bl.class('Sun', 'NetObject')
bl.class('GuiCursor', 'SimObject')
bl.class('ConsoleLogger', 'SimObject')
bl.class('QuotaObject', 'SimObject')
bl.class('FileObject', 'SimObject')
bl.class('BanList', 'SimObject')
bl.class('GuiControlProfile', 'SimObject')
bl.class('MessageVector', 'SimObject')
bl.class('ActionMap', 'SimObject')
-- Auto-generated from game scripts
bl.type('ActionMap::blockBind:1', 'object')

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,3 @@
-- This Lua code provides some built-in utilities for writing Lua add-ons
-- It is eval'd automatically once BLLua3 has loaded the TS API and environment
-- It only has access to the sandboxed lua environment, just like user code.
@@ -8,9 +7,10 @@ ts = _bllua_ts
-- Provide limited OS functions
os = os or {}
---@diagnostic disable-next-line: duplicate-set-field
function os.time() return math.floor(tonumber(_bllua_ts.call('getSimTime'))/1000) end
function os.time() return math.floor(tonumber(_bllua_ts.call('getSimTime')) / 1000) end
---@diagnostic disable-next-line: duplicate-set-field
function os.clock() return tonumber(_bllua_ts.call('getSimTime'))/1000 end
function os.clock() return tonumber(_bllua_ts.call('getSimTime')) / 1000 end
-- Virtual file class, emulating a file object as returned by io.open
-- Used to wrap io.open to allow reading from zips (using TS)
@@ -18,145 +18,150 @@ function os.clock() return tonumber(_bllua_ts.call('getSimTime'))/1000 end
-- Can't read nulls, can't distinguish between CRLF and LF.
-- Todo someday: actually read the zip in lua?
local file_meta = {
read = function(file, mode)
file:_init()
if not file or type(file)~='table' or not file._is_file then error('File:read: Not a file', 2) end
if file._is_open ~= true then error('File:read: File is closed', 2) end
if mode=='*n' then
local ws, n = file.data:match('^([ \t\r\n]*)([0-9%.%-e]+)', file.pos)
if n then
file.pos = file.pos + #ws + #n
return n
else
return nil
end
elseif mode=='*a' then
local d = file.data:sub(file.pos, #file.data)
file.pos = #file.data + 1
return d
elseif mode=='*l' then
local l, ws = file.data:match('^([^\r\n]*)(\r?\n)', file.pos)
if not l then
l = file.data:match('^([^\r\n]*)$', file.pos); ws = '';
if l=='' then return nil end
end
if l then
file.pos = file.pos + #l + #ws
return l
else
return nil
end
elseif type(mode)=='number' then
local d = file.data:sub(file.pos, file.pos+mode)
file.pos = file.pos + #d
return d
else
error('File:read: Invalid mode \''..mode..'\'', 2)
end
end,
lines = function(file)
file:_init()
return function()
return file:read('*l')
end
end,
close = function(file)
if not file._is_open then error('File:close: File is not open', 2) end
file._is_open = false
end,
__index = function(f, k) return rawget(f, k) or getmetatable(f)[k] end,
_init = function(f)
if not f.data then
f.data = _bllua_ts.call('_bllua_ReadEntireFile', f.filename)
end
end,
read = function(file, mode)
file:_init()
if not file or type(file) ~= 'table' or not file._is_file then error('File:read: Not a file', 2) end
if file._is_open ~= true then error('File:read: File is closed', 2) end
if mode == '*n' then
local ws, n = file.data:match('^([ \t\r\n]*)([0-9%.%-e]+)', file.pos)
if n then
file.pos = file.pos + #ws + #n
return n
else
return nil
end
elseif mode == '*a' then
local d = file.data:sub(file.pos, #file.data)
file.pos = #file.data + 1
return d
elseif mode == '*l' then
local l, ws = file.data:match('^([^\r\n]*)(\r?\n)', file.pos)
if not l then
l = file.data:match('^([^\r\n]*)$', file.pos); ws = '';
if l == '' then return nil end
end
if l then
file.pos = file.pos + #l + #ws
return l
else
return nil
end
elseif type(mode) == 'number' then
local d = file.data:sub(file.pos, file.pos + mode)
file.pos = file.pos + #d
return d
else
error('File:read: Invalid mode \'' .. mode .. '\'', 2)
end
end,
lines = function(file)
file:_init()
return function()
return file:read('*l')
end
end,
close = function(file)
if not file._is_open then error('File:close: File is not open', 2) end
file._is_open = false
end,
__index = function(f, k) return rawget(f, k) or getmetatable(f)[k] end,
_init = function(f)
if not f.data then
f.data = _bllua_ts.call('_bllua_ReadEntireFile', f.filename)
end
end,
}
local function new_file_obj(fn)
local file = {
_is_file = true,
_is_open = true,
pos = 1,
__index = file_meta.__index,
filename = fn,
data = nil,
}
setmetatable(file, file_meta)
return file
local file = {
_is_file = true,
_is_open = true,
pos = 1,
__index = file_meta.__index,
filename = fn,
data = nil,
}
setmetatable(file, file_meta)
return file
end
local function tflip(t) local u = {}; for _, n in ipairs(t) do u[n] = true end; return u; end
local allowed_zip_dirs = tflip{
'add-ons', 'base', 'config', 'saves', 'screenshots', 'shaders'
local function tflip(t)
local u = {}; for _, n in ipairs(t) do u[n] = true end; return u;
end
local allowed_zip_dirs = tflip {
'add-ons', 'base', 'config', 'saves', 'screenshots', 'shaders'
}
local function io_open_absolute(fn, mode)
-- if file exists, use original mode
local res, err = _bllua_io_open(fn, mode)
if res then return res end
-- otherwise, if TS sees file but Lua doesn't, it must be in a zip, so use TS reader
local dir = fn:match('^[^/]+')
if not allowed_zip_dirs[dir:lower()] then return nil, 'File is not in one of the allowed directories' end
local exist = _bllua_ts.call('isFile', fn) == '1'
if not exist then return nil, err end
if mode~=nil and mode~='r' and mode~='rb' then
return nil, 'Files in zips can only be opened in read mode' end
-- return a temp lua file object with the data
local fi = new_file_obj(fn)
return fi
-- if file exists, use original mode
local res, err = _bllua_io_open(fn, mode)
if res then return res end
-- otherwise, if TS sees file but Lua doesn't, it must be in a zip, so use TS reader
local dir = fn:match('^[^/]+')
if not allowed_zip_dirs[dir:lower()] then return nil, 'File is not in one of the allowed directories' end
local exist = _bllua_ts.call('isFile', fn) == '1'
if not exist then return nil, err end
if mode ~= nil and mode ~= 'r' and mode ~= 'rb' then
return nil, 'Files in zips can only be opened in read mode'
end
-- return a temp lua file object with the data
local fi = new_file_obj(fn)
return fi
end
io = io or {}
---@diagnostic disable-next-line: duplicate-set-field
function io.open(fn, mode, errn)
errn = errn or 1
-- try to open the file with relative path, otherwise use absolute path
local curfn = debug.getfilename(errn + 1) or _bllua_ts.getvar('Con::File')
if curfn == '' then curfn = nil end
if fn:find('^%.') then
local relfn = curfn and fn:find('^%./') and
curfn:gsub('[^/]+$', '')..fn:gsub('^%./', '')
if relfn then
local fi, err = io_open_absolute(relfn, mode)
return fi, err, relfn
else
return nil, 'Invalid path', fn
end
else
local fi, err = io_open_absolute(fn, mode)
return fi, err, fn
end
errn = errn or 1
-- try to open the file with relative path, otherwise use absolute path
local curfn = debug.getfilename(errn + 1) or _bllua_ts.getvar('Con::File')
if curfn == '' then curfn = nil end
if fn:find('^%.') then
local relfn = curfn and fn:find('^%./') and
curfn:gsub('[^/]+$', '') .. fn:gsub('^%./', '')
if relfn then
local fi, err = io_open_absolute(relfn, mode)
return fi, err, relfn
else
return nil, 'Invalid path', fn
end
else
local fi, err = io_open_absolute(fn, mode)
return fi, err, fn
end
end
---@diagnostic disable-next-line: duplicate-set-field
function io.lines(fn)
local fi, err, fn2 = io.open(fn, nil, 2)
if not fi then error('Error opening file \''..fn2..'\': '..err, 2) end
return fi:lines()
local fi, err, fn2 = io.open(fn, nil, 2)
if not fi then error('Error opening file \'' .. fn2 .. '\': ' .. err, 2) end
return fi:lines()
end
---@diagnostic disable-next-line: duplicate-set-field
function io.type(f)
---@diagnostic disable-next-line: undefined-field
if type(f)=='table' and f._is_file then
---@diagnostic disable-next-line: undefined-field
return f._is_open and 'file' or 'closed file'
else
return _bllua_io_type(f)
end
---@diagnostic disable-next-line: undefined-field
if type(f) == 'table' and f._is_file then
---@diagnostic disable-next-line: undefined-field
return f._is_open and 'file' or 'closed file'
else
return _bllua_io_type(f)
end
end
-- provide dofile
function dofile(fn, errn)
errn = errn or 1
local fi, err, fn2 = io.open(fn, 'r', errn+1)
if not fi then error('Error executing file \''..fn2..'\': '..err, errn+1) end
print('Executing '..fn2)
local text = fi:read('*a')
fi:close()
return assert(loadstring('--[['..fn2..']]'..text))()
errn = errn or 1
local fi, err, fn2 = io.open(fn, 'r', errn + 1)
if not fi then error('Error executing file \'' .. fn2 .. '\': ' .. err, errn + 1) end
print('Executing ' .. fn2)
local text = fi:read('*a')
fi:close()
return assert(loadstring('--[[' .. fn2 .. ']]' .. text))()
end
-- provide require (just a wrapper for dofile)
@@ -165,63 +170,67 @@ end
-- blockland directory
-- current add-on
local function file_exists(fn, errn)
local fi, err, fn2 = io.open(fn, 'r', errn+1)
if fi then
fi:close()
return fn2
else
return nil
end
local fi, err, fn2 = io.open(fn, 'r', errn + 1)
if fi then
fi:close()
return fn2
else
return nil
end
end
local require_memo = {}
function require(mod)
if require_memo[mod] then return unpack(require_memo[mod]) end
local fp = mod:gsub('%.', '/')
local fns = {
'./'..fp..'.lua', -- local file
'./'..fp..'/init.lua', -- local library
fp..'.lua', -- global file
fp..'/init.lua', -- global library
}
if fp:lower():find('^add-ons/') then
local addonpath = fp:lower():match('^add-ons/[^/]+')..'/'
table.insert(fns, addonpath..fp..'.lua') -- add-on file
table.insert(fns, addonpath..fp..'/init.lua') -- add-on library
end
for _,fn in ipairs(fns) do
local fne = file_exists(fn, 2)
if fne then
local res = {dofile(fne, 2)}
require_memo[mod] = res
return unpack(res)
end
end
return _bllua_requiresecure(mod)
if require_memo[mod] then return unpack(require_memo[mod]) end
local fp = mod:gsub('%.', '/')
local fns = {
'./' .. fp .. '.lua', -- local file
'./' .. fp .. '/init.lua', -- local library
fp .. '.lua', -- global file
fp .. '/init.lua', -- global library
}
if fp:lower():find('^add-ons/') then
local addonpath = fp:lower():match('^add-ons/[^/]+') .. '/'
table.insert(fns, addonpath .. fp .. '.lua') -- add-on file
table.insert(fns, addonpath .. fp .. '/init.lua') -- add-on library
end
for _, fn in ipairs(fns) do
local fne = file_exists(fn, 2)
if fne then
local res = { dofile(fne, 2) }
require_memo[mod] = res
return unpack(res)
end
end
return _bllua_requiresecure(mod)
end
-- Exposure to TS
function _bllua_getvar(name) return _G[name] end
function _bllua_setvar(name, val) _G[name] = val end
function _bllua_eval(code) return loadstring(code)() end
function _bllua_exec(fn) return dofile(fn, 2) end
local function isValidCode(code)
local f,e = loadstring(code)
return f~=nil
local f, e = loadstring(code)
return f ~= nil
end
function _bllua_smarteval(code)
if (not code:find('^print%(')) and isValidCode('print('..code..')') then
code = 'print('..code..')' end
local f,e = loadstring(code)
if f then
return f()
else
print(e)
end
if (not code:find('^print%(')) and isValidCode('print(' .. code .. ')') then
code = 'print(' .. code .. ')'
end
local f, e = loadstring(code)
if f then
return f()
else
print(e)
end
end
function ts.setvar(name, val)
_bllua_ts.call('_bllua_set_var', name, val)
_bllua_ts.call('_bllua_set_var', name, val)
end
_bllua_ts.call('echo', ' Executed libts-lua.lua')

View File

@@ -1,347 +1,374 @@
-- Basic functionality that should be standard in Lua
-- Table / List
-- Whether a table contains no keys
function table.empty(t)
return next(t)~=nil
return next(t) ~= nil
end
-- Apply a function to each key in a table
function table.map(f, ...)
local ts = {...}
local u = {}
for k,_ in pairs(ts[1]) do
local args = {}
for j=1,#ts do args[j] = ts[j][i] end
u[i] = f(unpack(args))
end
return u
local ts = { ... }
local u = {}
for k, _ in pairs(ts[1]) do
local args = {}
for j = 1, #ts do args[j] = ts[j][i] end
u[i] = f(unpack(args))
end
return u
end
function table.map_list(f, ...)
local ts = {...}
local u = {}
for i=1,#ts[1] do
local args = {}
for j=1,#ts do args[j] = ts[j][i] end
u[i] = f(unpack(args))
end
return u
local ts = { ... }
local u = {}
for i = 1, #ts[1] do
local args = {}
for j = 1, #ts do args[j] = ts[j][i] end
u[i] = f(unpack(args))
end
return u
end
-- Swap keys/values
function table.swap(t)
local u = {}
for k,v in pairs(t) do u[v] = k end
return u
local u = {}
for k, v in pairs(t) do u[v] = k end
return u
end
-- Reverse a list
function table.reverse(l)
local m = {}
for i=1,#l do m[#l-i+1] = l[i] end
return m
local m = {}
for i = 1, #l do m[#l - i + 1] = l[i] end
return m
end
-- Whether a table is a list/array (has only monotonic integer keys)
function table.islist(t)
local n = 0
for i,_ in pairs(t) do
if type(i)~='number' or i%1~=0 then return false end
n = n+1
end
return n==#t
local n = 0
for i, _ in pairs(t) do
if type(i) ~= 'number' or i % 1 ~= 0 then return false end
n = n + 1
end
return n == #t
end
-- Append contents of other tables to first table
function table.append(t, ...)
local a = {...}
for _,u in ipairs(a) do
for _,v in ipairs(u) do table.insert(t,v) end
end
return t
local a = { ... }
for _, u in ipairs(a) do
for _, v in ipairs(u) do table.insert(t, v) end
end
return t
end
-- Create a new table containing all keys from any number of tables
-- latter tables in the arg list override prior ones
-- overlaps, NOT appends, integer keys
function table.join(...)
local ts = {...}
local w = {}
for _,t in ipairs(ts) do
for k,v in pairs(t) do w[k] = v end
end
return w
local ts = { ... }
local w = {}
for _, t in ipairs(ts) do
for k, v in pairs(t) do w[k] = v end
end
return w
end
-- Whether a table contains a certain value in any key
function table.contains(t,s)
for _,v in pairs(t) do
if v==s then return true end
end
return false
function table.contains(t, s)
for _, v in pairs(t) do
if v == s then return true end
end
return false
end
function table.contains_list(t,s)
for _,v in ipairs(t) do
if v==s then return true end
end
return false
function table.contains_list(t, s)
for _, v in ipairs(t) do
if v == s then return true end
end
return false
end
-- Copy a table to another table
function table.copy(t)
local u = {}
for k,v in pairs(t) do u[k] = v end
return u
local u = {}
for k, v in pairs(t) do u[k] = v end
return u
end
function table.copy_list(l)
local m = {}
for i,v in ipairs(l) do m[i] = v end
return m
local m = {}
for i, v in ipairs(l) do m[i] = v end
return m
end
-- Sort a table in a new copy
function table.sortcopy(t, f)
local u = table.copy_list(t)
table.sort(u, f)
return u
local u = table.copy_list(t)
table.sort(u, f)
return u
end
-- Remove a value from a table
function table.removevalue(t, r)
local rem = {}
for k,v in pairs(t) do
if v==r then table.insert(rem, k) end
end
for _,k in ipairs(rem) do t[k] = nil end
local rem = {}
for k, v in pairs(t) do
if v == r then table.insert(rem, k) end
end
for _, k in ipairs(rem) do t[k] = nil end
end
function table.removevalue_list(t, r)
for i = #t, 1, -1 do
if t[i]==r then
table.remove(t, i)
end
end
for i = #t, 1, -1 do
if t[i] == r then
table.remove(t, i)
end
end
end
-- Export tables into formatted executable strings
local function tabs(tabLevel)
return (' '):rep(tabLevel)
return (' '):rep(tabLevel)
end
local valueToString
local function tableToString(t, tabLevel, seen)
if type(t)~='table' or (getmetatable(t) and getmetatable(t).__tostring) then
return tostring(t)
elseif table.islist(t) then
if #t==0 then
return '{}'
else
local strs = {}
local containsTables = false
for _,v in ipairs(t) do
if type(v)=='table' then containsTables = true end
table.insert(strs, valueToString(v, tabLevel+1, seen)..',')
end
if containsTables or #t>3 then
return '{\n'..tabs(tabLevel+1)
..table.concat(strs, '\n'..tabs(tabLevel+1))
..'\n'..tabs(tabLevel)..'}'
else
return '{ '..table.concat(strs, ' ')..' }'
end
end
else
local containsNonStringKeys = false
for k,v in pairs(t) do
if type(k)~='string' or k:find('[^a-zA-Z0-9_]') then
containsNonStringKeys = true
elseif type(k)=='table' then
error('table.tostring: table contains a table as key, cannot serialize')
end
end
local strs = {}
if containsNonStringKeys then
for k,v in pairs(t) do
table.insert(strs, '\n'..tabs(tabLevel+1)
..'['..valueToString(k, tabLevel+1, seen)..'] = '
..valueToString(v, tabLevel+1, seen)..',')
end
else
for k,v in pairs(t) do
table.insert(strs, '\n'..tabs(tabLevel+1)
..k..' = '..valueToString(v, tabLevel+1, seen)..',')
end
end
return '{'..table.concat(strs)..'\n'..tabs(tabLevel)..'}'
end
if type(t) ~= 'table' or (getmetatable(t) and getmetatable(t).__tostring) then
return tostring(t)
elseif table.islist(t) then
if #t == 0 then
return '{}'
else
local strs = {}
local containsTables = false
for _, v in ipairs(t) do
if type(v) == 'table' then containsTables = true end
table.insert(strs, valueToString(v, tabLevel + 1, seen) .. ',')
end
if containsTables or #t > 3 then
return '{\n' .. tabs(tabLevel + 1)
.. table.concat(strs, '\n' .. tabs(tabLevel + 1))
.. '\n' .. tabs(tabLevel) .. '}'
else
return '{ ' .. table.concat(strs, ' ') .. ' }'
end
end
else
local containsNonStringKeys = false
for k, v in pairs(t) do
if type(k) ~= 'string' or k:find('[^a-zA-Z0-9_]') then
containsNonStringKeys = true
elseif type(k) == 'table' then
error('table.tostring: table contains a table as key, cannot serialize')
end
end
local strs = {}
if containsNonStringKeys then
for k, v in pairs(t) do
table.insert(strs, '\n' .. tabs(tabLevel + 1)
.. '[' .. valueToString(k, tabLevel + 1, seen) .. '] = '
.. valueToString(v, tabLevel + 1, seen) .. ',')
end
else
for k, v in pairs(t) do
table.insert(strs, '\n' .. tabs(tabLevel + 1)
.. k .. ' = ' .. valueToString(v, tabLevel + 1, seen) .. ',')
end
end
return '{' .. table.concat(strs) .. '\n' .. tabs(tabLevel) .. '}'
end
end
valueToString = function(v, tabLevel, seen)
local t = type(v)
if t=='table' then
if seen[v] then
return 'nil --[[ already seen: '..tostring(v)..' ]]'
else
seen[v] = true
return tableToString(v, tabLevel, seen)
end
elseif t=='string' then
return '\''..string.escape(v)..'\''
elseif t=='number' or t=='boolean' then
return tostring(v)
else
--error('table.tostring: table contains a '..t..' value, cannot serialize')
return 'nil --[[ cannot serialize '..t..': '..tostring(v)..' ]]'
end
local t = type(v)
if t == 'table' then
if seen[v] then
return 'nil --[[ already seen: ' .. tostring(v) .. ' ]]'
else
seen[v] = true
return tableToString(v, tabLevel, seen)
end
elseif t == 'string' then
return '\'' .. string.escape(v) .. '\''
elseif t == 'number' or t == 'boolean' then
return tostring(v)
else
--error('table.tostring: table contains a '..t..' value, cannot serialize')
return 'nil --[[ cannot serialize ' .. t .. ': ' .. tostring(v) .. ' ]]'
end
end
function table.tostring(t)
return tableToString(t, 0, {})
return tableToString(t, 0, {})
end
-- String
-- Split string into table by separator
-- or by chars if no separator given
-- if regex is not true, sep is treated as a regex pattern
function string.split(str, sep, noregex)
if type(str)~='string' then
error('string.split: argument #1: expected string, got '..type(str), 2) end
if sep==nil or sep=='' then
local t = {}
local ns = #str
for x = 1, ns do
table.insert(t, str:sub(x, x))
end
return t
elseif type(sep)=='string' then
local t = {}
if #str>0 then
local first = 1
while true do
local last, newfirst = str:find(sep, first, noregex)
if not last then break end
table.insert(t, str:sub(first, last-1))
first = newfirst+1
end
table.insert(t, str:sub(first, #str))
end
return t
else
error(
'string.split: argument #2: expected string or nil, got '..type(sep), 2)
end
end
-- Split string to a list of char bytes
function string.bytes(s)
local b = {}
for i=1,#s do
local c = s:sub(i,i)
table.insert(b, c:byte())
end
return b
end
-- Trim leading and trailing whitespace
function string.trim(s, ws)
ws = ws or ' \t\r\n'
return s:gsub('^['..ws..']+', ''):gsub('['..ws..']+$', '')..''
end
-- String slicing and searching using [] operator
local str_meta = getmetatable('')
local str_meta_index_old= str_meta.__index
function str_meta.__index(s,k)
if type(k)=='string' then
return str_meta_index_old[k]
elseif type(k)=='number' then
if k<0 then k = #s+k+1 end
return string.sub(s,k,k)
elseif type(k)=='table' then
local a = k[1]<0 and (#s+k[1]+1) or k[1]
local b = k[2]<0 and (#s+k[2]+1) or k[2]
return string.sub(s,a,b)
end
end
-- String iterator
function string.chars(s)
local i = 0
return function()
i = i+1
if i<=#s then return s:sub(i,i)
else return nil end
end
end
-- Escape sequences
local defaultEscapes = {
['\\'] = '\\\\',
['\''] = '\\\'',
['\"'] = '\\\"',
['\t'] = '\\t',
['\r'] = '\\r',
['\n'] = '\\n',
['\0'] = '\\0',
}
function string.escape(s, escapes)
escapes = escapes or defaultEscapes
local t = {}
for i=1,#s do
local c = s:sub(i,i)
table.insert(t, escapes[c] or c)
end
return table.concat(t)
end
local defaultEscapeChar = '\\'
local defaultUnescapes = {
['\\'] = '\\',
['\''] = '\'',
['\"'] = '\"',
['t'] = '\t',
['r'] = '\r',
['n'] = '\n',
['0'] = '\0',
}
function string.unescape(s, escapeChar, unescapes)
escapeChar = escapeChar or defaultEscapeChar
unescapes = unescapes or defaultUnescapes
local t = {}
local inEscape = false
for i=1,#s do
local c = s:sub(i,i)
if inEscape then
table.insert(t, unescapes[c]
or error('string.unescape: invalid escape sequence: \''
..escapeChar..c..'\''))
elseif c==escapeChar then
inEscape = true
else
table.insert(t, c)
end
end
return table.concat(t)
if type(str) ~= 'string' then
error('string.split: argument #1: expected string, got ' .. type(str), 2)
end
if sep == nil or sep == '' then
local t = {}
local ns = #str
for x = 1, ns do
table.insert(t, str:sub(x, x))
end
return t
elseif type(sep) == 'string' then
local t = {}
if #str > 0 then
local first = 1
while true do
local last, newfirst = str:find(sep, first, noregex)
if not last then break end
table.insert(t, str:sub(first, last - 1))
first = newfirst + 1
end
table.insert(t, str:sub(first, #str))
end
return t
else
error(
'string.split: argument #2: expected string or nil, got ' .. type(sep), 2)
end
end
-- Split string to a list of char bytes
function string.bytes(s)
local b = {}
for i = 1, #s do
local c = s:sub(i, i)
table.insert(b, c:byte())
end
return b
end
-- Trim leading and trailing whitespace
function string.trim(s, ws)
ws = ws or ' \t\r\n'
return s:gsub('^[' .. ws .. ']+', ''):gsub('[' .. ws .. ']+$', '') .. ''
end
-- String slicing and searching using [] operator
local str_meta = getmetatable('')
local str_meta_index_old = str_meta.__index
function str_meta.__index(s, k)
if type(k) == 'string' then
return str_meta_index_old[k]
elseif type(k) == 'number' then
if k < 0 then k = #s + k + 1 end
return string.sub(s, k, k)
elseif type(k) == 'table' then
local a = k[1] < 0 and (#s + k[1] + 1) or k[1]
local b = k[2] < 0 and (#s + k[2] + 1) or k[2]
return string.sub(s, a, b)
end
end
-- String iterator
function string.chars(s)
local i = 0
return function()
i = i + 1
if i <= #s then
return s:sub(i, i)
else
return nil
end
end
end
-- Escape sequences
local defaultEscapes = {
['\\'] = '\\\\',
['\''] = '\\\'',
['\"'] = '\\\"',
['\t'] = '\\t',
['\r'] = '\\r',
['\n'] = '\\n',
['\0'] = '\\0',
}
function string.escape(s, escapes)
escapes = escapes or defaultEscapes
local t = {}
for i = 1, #s do
local c = s:sub(i, i)
table.insert(t, escapes[c] or c)
end
return table.concat(t)
end
local defaultEscapeChar = '\\'
local defaultUnescapes = {
['\\'] = '\\',
['\''] = '\'',
['\"'] = '\"',
['t'] = '\t',
['r'] = '\r',
['n'] = '\n',
['0'] = '\0',
}
function string.unescape(s, escapeChar, unescapes)
escapeChar = escapeChar or defaultEscapeChar
unescapes = unescapes or defaultUnescapes
local t = {}
local inEscape = false
for i = 1, #s do
local c = s:sub(i, i)
if inEscape then
table.insert(t, unescapes[c]
or error('string.unescape: invalid escape sequence: \''
.. escapeChar .. c .. '\''))
elseif c == escapeChar then
inEscape = true
else
table.insert(t, c)
end
end
return table.concat(t)
end
-- IO
io = io or {}
-- Read entire file at once, return nil,err if access failed
function io.readall(filename)
local fi,err = io.open(filename, 'rb')
if not fi then return nil,err end
local s = fi:read("*a")
fi:close()
return s
end
-- Write data to file all at once, return true if success / false,err if failure
function io.writeall(filename, data)
local fi,err = io.open(filename, 'wb')
if not fi then return false,err end
fi:write(data)
fi:close()
return true,nil
local fi, err = io.open(filename, 'rb')
if not fi then return nil, err end
local s = fi:read("*a")
fi:close()
return s
end
-- Write data to file all at once, return true if success / false,err if failure
function io.writeall(filename, data)
local fi, err = io.open(filename, 'wb')
if not fi then return false, err end
fi:write(data)
fi:close()
return true, nil
end
-- Math
-- Round
function math.round(x)
return math.floor(x+0.5)
return math.floor(x + 0.5)
end
-- Mod that accounts for floating point inaccuracy
function math.mod(a,b)
local m = a%b
if m==0 or math.abs(m)<1e-15 or math.abs(m-b)<1e-15 then return 0
else return m end
function math.mod(a, b)
local m = a % b
if m == 0 or math.abs(m) < 1e-15 or math.abs(m - b) < 1e-15 then
return 0
else
return m
end
end
-- Clamp value between min and max
function math.clamp(v, n, x)
return math.min(x, math.max(v, n))
return math.min(x, math.max(v, n))
end

View File

@@ -1,218 +1,237 @@
-- Vector math class with operators
local vector_meta
local vector_new
local function vector_check(v, n, name, argn)
if not v.__is_vector then
error('vector '..name..': argument #'..(argn or 1)
..': expected vector, got '..type(v), n+1) end
if not v.__is_vector then
error('vector ' .. name .. ': argument #' .. (argn or 1)
.. ': expected vector, got ' .. type(v), n + 1)
end
end
local function vector_checksamelen(v1, v2, name)
vector_check(v1, 3, name, 1)
vector_check(v2, 3, name, 2)
if #v1~=#v2 then
error('vector '..name..': vector lengths do not match (lengths are '
..#v1..' and '..#v2..')', 3) end
return #v1
vector_check(v1, 3, name, 1)
vector_check(v2, 3, name, 2)
if #v1 ~= #v2 then
error('vector ' .. name .. ': vector lengths do not match (lengths are '
.. #v1 .. ' and ' .. #v2 .. ')', 3)
end
return #v1
end
local function vector_checklen(v1, v2, name, len)
vector_check(v1, 3, name, 1)
vector_check(v2, 3, name, 2)
if #v1~=len or #v2~=len then
error('vector '..name..': vector lengths are not '..len..' (lengths are '
..#v1..' and '..#v2..')', 3) end
vector_check(v1, 3, name, 1)
vector_check(v2, 3, name, 2)
if #v1 ~= len or #v2 ~= len then
error('vector ' .. name .. ': vector lengths are not ' .. len .. ' (lengths are '
.. #v1 .. ' and ' .. #v2 .. ')', 3)
end
end
local function vector_opnnn(name, op)
return function(v1, v2)
local len = vector_checksamelen(v1, v2, name)
local v3 = {}
for i = 1, len do
v3[i] = op(v1[i], v2[i])
end
return vector_new(v3)
end
return function(v1, v2)
local len = vector_checksamelen(v1, v2, name)
local v3 = {}
for i = 1, len do
v3[i] = op(v1[i], v2[i])
end
return vector_new(v3)
end
end
local function vector_opnxn(name, op)
return function(v1, v2)
local v1v = type(v1)=='table' and v1.__is_vector
local v2v = type(v2)=='table' and v2.__is_vector
if v1v and v2v then
local len = vector_checksamelen(v1, v2, name)
local v3 = {}
for i = 1, len do
v3[i] = op(v1[i], v2[i])
end
return vector_new(v3)
else
if v2v then v1,v2 = v2,v1 end
local len = #v1
local v3 = {}
for i = 1, len do
v3[i] = op(v1[i], v2)
end
return vector_new(v3)
end
end
return function(v1, v2)
local v1v = type(v1) == 'table' and v1.__is_vector
local v2v = type(v2) == 'table' and v2.__is_vector
if v1v and v2v then
local len = vector_checksamelen(v1, v2, name)
local v3 = {}
for i = 1, len do
v3[i] = op(v1[i], v2[i])
end
return vector_new(v3)
else
if v2v then v1, v2 = v2, v1 end
local len = #v1
local v3 = {}
for i = 1, len do
v3[i] = op(v1[i], v2)
end
return vector_new(v3)
end
end
end
local function vector_opn0n(name, op)
return function(v1)
--vector_check(v1, 1, name)
local len = #v1
local v2 = {}
for i = 1, len do
v2[i] = op(v1[i])
end
return vector_new(v2)
end
return function(v1)
--vector_check(v1, 1, name)
local len = #v1
local v2 = {}
for i = 1, len do
v2[i] = op(v1[i])
end
return vector_new(v2)
end
end
local vector_indices = {x = 1, y = 2, z = 3, w = 4, r = 1, g = 2, b = 3, a = 4}
local vector_indices = { x = 1, y = 2, z = 3, w = 4, r = 1, g = 2, b = 3, a = 4 }
local vector_meta = {
__is_vector = true,
__index = function(t, k)
if tonumber(k) then return rawget(t, k)
elseif vector_indices[k] then return rawget(t, vector_indices[k])
else return getmetatable(t)[k]
end
end,
__newindex = function(t, k, v)
if tonumber(k) then rawset(t, k, v)
elseif vector_indices[k] then rawset(t, vector_indices[k], v)
else return
end
end,
__add = vector_opnnn('add', function(x1, x2) return x1+x2 end),
__sub = vector_opnnn('sub', function(x1, x2) return x1-x2 end),
__mul = vector_opnxn('mul', function(x1, x2) return x1*x2 end),
__div = vector_opnxn('div', function(x1, x2) return x1/x2 end),
__pow = vector_opnxn('pow', function(x1, x2) return x1^x2 end),
__unm = vector_opn0n('inv', function(x1) return -x1 end),
__concat = nil,
--__len = function(v1) return #v1 end,
__len = nil,
__eq = function(v1, v2)
local len = vector_checksamelen(v1, v2, 'equals')
for i = 1, len do
if v1[i]~=v2[i] then return false end
end
return true
end,
__lt = nil,
__le = nil,
__call = nil,
abs = vector_opn0n('abs', math.abs),
length = function(v1)
--vector_check(v1, 2, 'length')
local len = #v1
local l = 0
for i = 1, len do
l = l + v1[i]^2
end
return math.sqrt(l)
end,
normalize = function(v1)
--vector_check(v1, 2, 'normal')
local length = v1:length()
local len = #v1
local v3 = {}
for i = 1, len do
if length==0 then v3[i] = 0
else v3[i] = v1[i]/length end
end
return vector_new(v3)
end,
__tostring = function(v1)
--vector_check(v1, 2, 'tostring')
local st = {}
local len = #v1
for i = 1, len do
table.insert(st, tostring(v1[i]))
end
return 'vector{ '..table.concat(st, ', ')..' }'
end,
unpack = function(v1) return unpack(v1) end,
floor = vector_opn0n('floor', function(x1) return math.floor(x1) end),
ceil = vector_opn0n('ceil' , function(x1) return math.ceil (x1) end),
round = vector_opn0n('round', function(x1) return math.floor(x1+0.5) end),
dot = function(v1, v2)
local len = vector_checksamelen(v1, v2, 'dot')
local x = 0
for i = 1, len do
x = x + v1[i]*v2[i]
end
return x
end,
cross = function(v1, v2)
vector_checklen(v1, v2, 'cross', 3)
return vector_new{
v1[2]*v2[3] - v1[3]*v2[2],
v1[3]*v2[1] - v1[1]*v2[3],
v1[1]*v2[2] - v1[2]*v2[1],
}
end,
rotateByAngleId = function(v1, r)
--vector_check(v1, 2, 'rotate')
if type(r)~='number' or r%1~=0 then
error('vector rotateByAngleId: invalid rotation '..tostring(r), 2) end
r = r%4
local v2
if r==0 then v2 = vector_new{ v1[1], v1[2], v1[3] }
elseif r==1 then v2 = vector_new{ v1[2], -v1[1], v1[3] }
elseif r==2 then v2 = vector_new{ -v1[1], -v1[2], v1[3] }
elseif r==3 then v2 = vector_new{ -v1[2], v1[1], v1[3] }
else error('vector rotateByAngleId: invalid rotation '..r, 2) end
return v2
end,
rotateZ = function(v, r)
--vector_check(v, 2, 'rotate2d')
if type(r)~='number' then
error('vector rotateZ: invalid rotation '..tostring(r), 2) end
local len = math.sqrt(v[1]^2 + v[2]^2)
local ang = math.atan2(v[2], v[1]) + r
local v2 = vector_new{ math.cos(ang)*len, math.sin(ang)*len }
return v2
end,
tsString = function(v)
--vector_check(v, 2, 'tsString')
return table.concat(v, ' ')
end,
distance = function(v1, v2)
local len = vector_checksamelen(v1, v2, 'distance')
local sum = 0
for i=1,len do
sum = sum + (v1[i] - v2[i])^2
end
return math.sqrt(sum)
end,
copy = function(v)
--vector_check(v, 2, 'copy')
return vector_new(v)
end,
__is_vector = true,
__index = function(t, k)
if tonumber(k) then
return rawget(t, k)
elseif vector_indices[k] then
return rawget(t, vector_indices[k])
else
return getmetatable(t)[k]
end
end,
__newindex = function(t, k, v)
if tonumber(k) then
rawset(t, k, v)
elseif vector_indices[k] then
rawset(t, vector_indices[k], v)
else
return
end
end,
__add = vector_opnnn('add', function(x1, x2) return x1 + x2 end),
__sub = vector_opnnn('sub', function(x1, x2) return x1 - x2 end),
__mul = vector_opnxn('mul', function(x1, x2) return x1 * x2 end),
__div = vector_opnxn('div', function(x1, x2) return x1 / x2 end),
__pow = vector_opnxn('pow', function(x1, x2) return x1 ^ x2 end),
__unm = vector_opn0n('inv', function(x1) return -x1 end),
__concat = nil,
--__len = function(v1) return #v1 end,
__len = nil,
__eq = function(v1, v2)
local len = vector_checksamelen(v1, v2, 'equals')
for i = 1, len do
if v1[i] ~= v2[i] then return false end
end
return true
end,
__lt = nil,
__le = nil,
__call = nil,
abs = vector_opn0n('abs', math.abs),
length = function(v1)
--vector_check(v1, 2, 'length')
local len = #v1
local l = 0
for i = 1, len do
l = l + v1[i] ^ 2
end
return math.sqrt(l)
end,
normalize = function(v1)
--vector_check(v1, 2, 'normal')
local length = v1:length()
local len = #v1
local v3 = {}
for i = 1, len do
if length == 0 then
v3[i] = 0
else
v3[i] = v1[i] / length
end
end
return vector_new(v3)
end,
__tostring = function(v1)
--vector_check(v1, 2, 'tostring')
local st = {}
local len = #v1
for i = 1, len do
table.insert(st, tostring(v1[i]))
end
return 'vector{ ' .. table.concat(st, ', ') .. ' }'
end,
unpack = function(v1) return unpack(v1) end,
floor = vector_opn0n('floor', function(x1) return math.floor(x1) end),
ceil = vector_opn0n('ceil', function(x1) return math.ceil(x1) end),
round = vector_opn0n('round', function(x1) return math.floor(x1 + 0.5) end),
dot = function(v1, v2)
local len = vector_checksamelen(v1, v2, 'dot')
local x = 0
for i = 1, len do
x = x + v1[i] * v2[i]
end
return x
end,
cross = function(v1, v2)
vector_checklen(v1, v2, 'cross', 3)
return vector_new {
v1[2] * v2[3] - v1[3] * v2[2],
v1[3] * v2[1] - v1[1] * v2[3],
v1[1] * v2[2] - v1[2] * v2[1],
}
end,
rotateByAngleId = function(v1, r)
--vector_check(v1, 2, 'rotate')
if type(r) ~= 'number' or r % 1 ~= 0 then
error('vector rotateByAngleId: invalid rotation ' .. tostring(r), 2)
end
r = r % 4
local v2
if r == 0 then
v2 = vector_new { v1[1], v1[2], v1[3] }
elseif r == 1 then
v2 = vector_new { v1[2], -v1[1], v1[3] }
elseif r == 2 then
v2 = vector_new { -v1[1], -v1[2], v1[3] }
elseif r == 3 then
v2 = vector_new { -v1[2], v1[1], v1[3] }
else
error('vector rotateByAngleId: invalid rotation ' .. r, 2)
end
return v2
end,
rotateZ = function(v, r)
--vector_check(v, 2, 'rotate2d')
if type(r) ~= 'number' then
error('vector rotateZ: invalid rotation ' .. tostring(r), 2)
end
local len = math.sqrt(v[1] ^ 2 + v[2] ^ 2)
local ang = math.atan2(v[2], v[1]) + r
local v2 = vector_new { math.cos(ang) * len, math.sin(ang) * len }
return v2
end,
tsString = function(v)
--vector_check(v, 2, 'tsString')
return table.concat(v, ' ')
end,
distance = function(v1, v2)
local len = vector_checksamelen(v1, v2, 'distance')
local sum = 0
for i = 1, len do
sum = sum + (v1[i] - v2[i]) ^ 2
end
return math.sqrt(sum)
end,
copy = function(v)
--vector_check(v, 2, 'copy')
return vector_new(v)
end,
}
vector_new = function(vi)
if vi then
if type(vi)=='string' then
local vi2 = {}
for val in vi:gmatch('[0-9%.%-e]+') do
table.insert(vi2, tonumber(val))
end
vi = vi2
elseif type(vi)~='table' then
error('vector: argument #1: expected input table, got '..type(vi), 2)
end
local v = {}
if #vi>0 then
for i = 1, #vi do v[i] = vi[i] end
else
for n, i in pairs(vector_indices) do v[i] = vi[n] end
if #v==0 then
error('vector: argument #1: table contains no values', 2)
end
end
setmetatable(v, vector_meta)
return v
else
error('vector: argument #1: expected input table, got nil', 2)
end
if vi then
if type(vi) == 'string' then
local vi2 = {}
for val in vi:gmatch('[0-9%.%-e]+') do
table.insert(vi2, tonumber(val))
end
vi = vi2
elseif type(vi) ~= 'table' then
error('vector: argument #1: expected input table, got ' .. type(vi), 2)
end
local v = {}
if #vi > 0 then
for i = 1, #vi do v[i] = vi[i] end
else
for n, i in pairs(vector_indices) do v[i] = vi[n] end
if #v == 0 then
error('vector: argument #1: table contains no values', 2)
end
end
setmetatable(v, vector_meta)
return v
else
error('vector: argument #1: expected input table, got nil', 2)
end
end
vector = vector_new