From e61bb07373fcbbc7d0ebaa2e35f28b5a97e3a0e0 Mon Sep 17 00:00:00 2001 From: Colby Klein Date: Wed, 4 Apr 2012 22:19:26 -0700 Subject: [PATCH] Add table manipulation helpers. Added: string.split (usage: string.split("1-2-3", "-") => { 1, 2, 3 }) Added: table.join (alias of table.concat, for convenience) Added: table.push (multiple element insert. usage: table.push(t, 1, 2, ...). Used extensively in optics) --- Scripts/extend_table.lua | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Scripts/extend_table.lua diff --git a/Scripts/extend_table.lua b/Scripts/extend_table.lua new file mode 100644 index 0000000000..8779a5f300 --- /dev/null +++ b/Scripts/extend_table.lua @@ -0,0 +1,38 @@ +-- Utilities for better table manipulation + +-- split a string into a table +-- http://lua-users.org/wiki/SplitJoin (but with error messages) +function string.split(self, sSeparator, nMax, bRegexp) + assert(sSeparator ~= '', "empty separator is not allowed.") + assert(nMax == nil or nMax >= 1, "max must be a positive number.") + + local aRecord = {} + + if self:len() > 0 then + local bPlain = not bRegexp + nMax = nMax or -1 + + local nField=1 nStart=1 + local nFirst,nLast = self:find(sSeparator, nStart, bPlain) + while nFirst and nMax ~= 0 do + aRecord[nField] = self:sub(nStart, nFirst-1) + nField = nField+1 + nStart = nLast+1 + nFirst,nLast = self:find(sSeparator, nStart, bPlain) + nMax = nMax-1 + end + aRecord[nField] = self:sub(nStart) + end + + return aRecord +end + +-- table.concat alias for convenience. +table.join = table.concat + +-- insert multiple elements into a table at once +function table.push(self, ...) + for _, v in ipairs({...}) do + table.insert(self, v) + end +end