Compare Lua and MiniScript

100 doors
LuaMiniScript
local is_open = {}

for pass = 1,100 do
    for door = pass,100,pass do
        is_open[door] = not is_open[door]
    end
end

for i,v in next,is_open do
    print ('Door '..i..':',v and 'open' or 'close')
end
d = {}
for p in range(1, 100)
    for t in range(p, 100, p)
        if d.hasIndex(t) then d.remove t else d.push t
    end for
end for

print d.indexes.sort
100 prisoners
LuaMiniScript
function shuffle(tbl)
  for i = #tbl, 2, -1 do
    local j = math.random(i)
    tbl[i], tbl[j] = tbl[j], tbl[i]
  end
  return tbl
end

function playOptimal()
    local secrets = {}
    for i=1,100 do
        secrets[i] = i
    end
    shuffle(secrets)

    for p=1,100 do
        local success = false

        local choice = p
        for i=1,50 do
            if secrets[choice] == p then
                success = true
                break
            end
            choice = secrets[choice]
        end

        if not success then
            return false
        end
    end

    return true
end

function playRandom()
    local secrets = {}
    for i=1,100 do
        secrets[i] = i
    end
    shuffle(secrets)

    for p=1,100 do
        local choices = {}
        for i=1,100 do
            choices[i] = i
        end
        shuffle(choices)

        local success = false
        for i=1,50 do
            if choices[i] == p then
                success = true
                break
            end
        end

        if not success then
            return false
        end
    end

    return true
end

function exec(n,play)
    local success = 0
    for i=1,n do
        if play() then
            success = success + 1
        end
    end
    return 100.0 * success / n
end

function main()
    local N = 1000000
    print("# of executions: "..N)
    print(string.format("Optimal play success rate: %f", exec(N, playOptimal)))
    print(string.format("Random play success rate: %f", exec(N, playRandom)))
end

main()
playRandom = function(n)
    // using 0-99 instead of 1-100
    pardoned = 0
    numInDrawer = range(99)
    choiceOrder = range(99)
    for round in range(1, n)
    	numInDrawer.shuffle
        choiceOrder.shuffle
        for prisoner in range(99)
            found = false
            for card in choiceOrder[:50]
                if card == prisoner then
                    found = true
                    break
                end if
            end for
            if not found then break
        end for
        if found then pardoned = pardoned + 1
    end for
    return pardoned / n * 100
end function

playOptimal = function(n)
    // using 0-99 instead of 1-100
    pardoned = 0
    numInDrawer = range(99)
    for round in range(1, n)
    	numInDrawer.shuffle
        for prisoner in range(99)
            found = false
	    drawer = prisoner
            for i in range(1,50)
                card = numInDrawer[drawer]
                if card == prisoner then
                    found = true
                    break
                end if
                drawer = card
            end for
            if not found then break
        end for
        if found then pardoned = pardoned + 1
    end for
    return pardoned / n * 100
end function

print "Random:  " + playRandom(10000) + "%"
print "Optimal: " + playOptimal(10000) + "%"
24 game
LuaMiniScript
local function help()
	print [[
 The 24 Game

 Given any four digits in the range 1 to 9, which may have repetitions,
 Using just the +, -, *, and / operators; and the possible use of
 brackets, (), show how to make an answer of 24.

 An answer of "q" will quit the game.
 An answer of "!" will generate a new set of four digits.

 Note: you cannot form multiple digit numbers from the supplied digits,
 so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

 ]]
end

local function generate(n)
	result = {}
	for i=1,n do
		result[i] = math.random(1,9)
	end
	return result
end

local function check(answer, digits)
	local adig = {}
	local ddig = {}
	local index
	local lastWasDigit = false
	for i=1,9 do adig[i] = 0 ddig[i] = 0 end
	allowed = {['(']=true,[')']=true,['
']=true,['+']=true,['-']=true,['*']=true,['/']=true,['\t']=true,['1']=true,['2']=true,['3']=true,['4
']=true,['5']=true,['6']=true,['7']=true,['8']=true,['9']=true}
	for i=1,string.len(answer) do
		if not allowed[string.sub(answer,i,i)] then
			return false
		end
		index = string.byte(answer,i)-48
		if index > 0 and index < 10 then
			if lastWasDigit then
				return false
			end
			lastWasDigit = true
			adig[index] = adig[index] + 1
		else
			lastWasDigit = false
		end
	end
	for i,digit in next,digits do
		ddig[digit] = ddig[digit]+1
	end
	for i=1,9 do
		if adig[i] ~= ddig[i] then
			return false
		end
	end
	return loadstring('return '..answer)()
end

local function game24()
	help()
	math.randomseed(os.time())
	math.random()
	local digits = generate(4)
	local trial = 0
	local answer = 0
	local ans = false
	io.write 'Your four digits:'
	for i,digit in next,digits do
		io.write (' ' .. digit)
	end
	print()
	while ans ~= 24 do
		trial = trial + 1
		io.write("Expression "..trial..": ")
		answer = io.read()
		if string.lower(answer) == 'q' then
			break
		end
		if answer == '!' then
			digits = generate(4)
			io.write ("New digits:")
			for i,digit in next,digits do
				io.write (' ' .. digit)
			end
			print()
		else
			ans = check(answer,digits)
			if ans == false then
				print ('The input '.. answer ..' was wonky!')
			else
				print (' = '.. ans)
				if ans == 24 then
					print ("Thats right!")
				end
			end
		end
	end
end
game24()
evalAddSub = function()
    result = evalMultDiv
    while true
        if not tokens then return result
        op = tokens[0]
        if op != "+" and op != "-" then return result
        tokens.pull  // (discard operator)
        rhs = evalMultDiv
        if result == null or rhs == null then return null
        if op == "+" then result = result + rhs
        if op == "-" then result = result - rhs
    end while
end function

evalMultDiv = function()
    result = evalAtom
    while true
        if not tokens then return result
        op = tokens[0]
        if op != "*" and op != "/" then return result
        tokens.pull  // (discard operator)
        rhs = evalAtom
        if result == null or rhs == null then return null
        if op == "*" then result = result * rhs
        if op == "/" then result = result / rhs
    end while
end function
    
evalAtom = function()
    if tokens[0] == "(" then
        tokens.pull
        result = evalAddSub
        if not tokens or tokens.pull != ")" then
            print "Unbalanced parantheses"
            return null
        end if
        return result
    end if
    num = val(tokens.pull)
    idx = availableDigits.indexOf(num)
    if idx == null then
        print str(num) + " is not available"
        return null
    else
        availableDigits.remove idx
    end if
    return num
end function

choices = []
for i in range(1, 4)
    choices.push ceil(rnd*9)
end for
result = null
while result != 24
    availableDigits = choices[:]  // (clones the list)
    print "Using only the digits " + availableDigits + ","
    tokens = input("enter an expression that comes to 24: ").replace(" ","").values
    result = evalAddSub
    if availableDigits then
        print "You forgot to use: " + availableDigits
        result = null
    end if
    if result != null then print "That equals " + result + "."
end while
print "Great job!"
99 bottles of beer
LuaMiniScript
local bottles = 99

local function plural (bottles) if bottles == 1 then return '' end return 's' end
while bottles > 0 do
    print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
    print (bottles..' bottle'..plural(bottles)..' of beer')
    print ('Take one down, pass it around')
    bottles = bottles - 1
    print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
    print ()
end
bottles = function(n)
    if n == 0 then return "no bottles"
    if n == 1 then return "1 bottle"
    return n + " bottles"
end function

verse = function(n)
    print bottles(n) + " of beer on the wall"
    print bottles(n) + " of beer"
    print "Take one down, pass it around"
    print bottles(n-1) + " of beer on the wall"
    print
end function

for i in range(99, 1)
    verse i
end for
A+B
LuaMiniScript
a,b = io.read("*number", "*number")
print(a+b)
s = "  2    3  "
fields = s.split
for i in range(fields.len-1, 0)
    if fields[i] == "" then fields.remove i
end for
if fields.len < 2 then
    print "Not enough input"
else
    print val(fields[0]) + val(fields[1])
end if
Abbreviations, simple
LuaMiniScript
abbr = {
  define = function(self, cmdstr)
    local cmd
    self.hash = {}
    for word in cmdstr:upper():gmatch("%S+") do
      if cmd then
        local n = tonumber(word)
        for len = n or #cmd, #cmd do
          self.hash[cmd:sub(1,len)] = cmd
        end
        cmd = n==nil and word or nil
      else
        cmd = word
      end
    end
  end,
  expand = function(self, input)
    local output = {}
    for word in input:upper():gmatch("%S+") do
      table.insert(output, self.hash[word] or "*error*")
    end
    return table.concat(output, " ")
  end
}
abbr:define[[
  add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
  compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
  3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
  forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
  locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
  msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
  refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
  2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1
]]
local input = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
print("Input:", input)
print("Output:", abbr:expand(input))
c = "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2 Clast 3" +
 " compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate" +
 " 3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2" +
 " forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load" +
 " locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2" +
 " msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3" +
 " refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left" +
 " 2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1"
 
minLen = {}
lastItem = ""
for item in c.split
    if item == "" then continue
    item = item.upper
    if lastItem and item[0] >= "0" and item[0] <= "9" then
        minLen[lastItem] = val(item)
        lastItem = ""
    else
        minLen[item] = null
        lastItem = item
    end if
end for
 
check = function(word)
    word = word.upper
    for key in minLen.indexes
        if key[:word.len] != word then continue
        min = minLen[key]
        if min and word.len < min then continue
        return key
    end for
    return "*error*"
end function
 
input = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
 
output = []
for word in input.split
    if word == "" then continue
    output.push check(word)
end for
print output.join
ABC problem
LuaMiniScript
blocks = {
	{"B","O"};	{"X","K"};	{"D","Q"};	{"C","P"};
	{"N","A"};	{"G","T"};	{"R","E"};	{"T","G"};
	{"Q","D"};	{"F","S"};	{"J","W"};	{"H","U"};
	{"V","I"};	{"A","N"};	{"O","B"};	{"E","R"};
	{"F","S"};	{"L","Y"};	{"P","C"};	{"Z","M"};
	};

function canUse(table, letter)
	for i,v in pairs(blocks) do
		if (v[1] == letter:upper() or v[2] == letter:upper())  and table[i] then
			table[i] = false;
			return true;
		end
	end
	return false;
end

function canMake(Word)
	local Taken = {};
	for i,v in pairs(blocks) do
		table.insert(Taken,true);
	end
	local found = true;
	for i = 1,#Word do
		if not canUse(Taken,Word:sub(i,i)) then
			found = false;
		end
	end
	print(found)
end
allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN",
"OB", "ER", "FS", "LY", "PC", "ZM"]
 
swap = function(list, index1, index2)
    tmp = list[index1]
    list[index1] = list[index2]
    list[index2] = tmp
end function
 
canMakeWord = function(str, blocks)
    if str == "" then return true
    c = str[0].upper
    for i in range(0, blocks.len - 1)
        bl = blocks[i]
        if c != bl[0] and c != bl[1] then continue
        swap blocks, 0, i
        if canMakeWord(str[1:], blocks[1:]) then return true
        swap blocks, 0, i
    end for
    return false
end function
 
for val in ["", "A", "BARK", "book", "Treat", "COMMON", "sQuAD", "CONFUSE"]
    out = """"""
    if val.len != 0 then out = val
    print out + ": " + canMakeWord(val, allBlocks)
end for
Ackermann function
LuaMiniScript
function ack(M,N)
    if M == 0 then return N + 1 end
    if N == 0 then return ack(M-1,1) end
    return ack(M-1,ack(M, N-1))
end
ackermann = function(m, n)
    if m == 0 then return n+1
    if n == 0 then return ackermann(m - 1, 1)
    return ackermann(m - 1, ackermann(m, n - 1))
end function
 
for m in range(0, 3)
    for n in range(0, 4)
        print "(" + m + ", " + n + "): " + ackermann(m, n)
    end for
end for
Add a variable to a class instance at runtime
LuaMiniScript
empty = {}
empty.foo = 1
empty = {}
empty.foo = 1
Animation
LuaMiniScript
function love.load()
	text = "Hello World! "
	length = string.len(text)
	
	
	update_time = 0.3
	timer = 0
	right_direction = true
	
	
	local width, height = love.graphics.getDimensions( )

	local size = 100
	local font = love.graphics.setNewFont( size )
	local twidth = font:getWidth( text )
	local theight = font:getHeight( )
	x = width/2 - twidth/2
	y = height/2-theight/2
	
end

 
function love.update(dt)
	timer = timer + dt
	if timer > update_time then
		timer = timer - update_time
		if right_direction then
			text = string.sub(text, 2, length) .. string.sub(text, 1, 1)
		else
			text = string.sub(text, length, length) .. string.sub(text, 1, length-1)
		end
	end
end


function love.draw()
	love.graphics.print (text, x, y)
end

function love.keypressed(key, scancode, isrepeat)
	if false then
	elseif key == "escape" then
		love.event.quit()
	end
end

function love.mousepressed( x, y, button, istouch, presses )
	right_direction = not right_direction
end
clear
text.inverse = true
s = "Hello World! "
while not key.available
	text.row = 12
	text.column = 15
	print " " + s + " "
	wait 0.1
	s = s[-1] + s[:-1]
end while
text.inverse = false
key.clear
Arithmetic evaluation
LuaMiniScript
require"lpeg"

P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V

--matches arithmetic expressions and returns a syntax tree
expression = P{"expr";
ws = P" "^0,
number = C(R"09"^1) * V"ws",
lp = "(" * V"ws",
rp = ")" * V"ws",
sym = C(S"+-*/") * V"ws",
more = (V"sym" * V"expr")^0,
expr = V"number" * V"more" + V"lp" * lpeg.Ct(V"expr" * V"more") * V"rp" * V"more"}

--evaluates a tree
function eval(expr)
  --empty
  if type(expr) == "string" or type(expr) == "number" then return expr + 0 end
  
  --arithmetic functions
  tb = {["+"] = function(a,b) return eval(a) + eval(b) end,
		["-"] = function(a,b) return eval(a) - eval(b) end,
		["*"] = function(a,b) return eval(a) * eval(b) end,
		["/"] = function(a,b) return eval(a) / eval(b) end}
  
  --you could add ^ or other operators to this pretty easily
  for i, v in ipairs{"*/", "+-"} do
    for s, u in ipairs(expr) do
	  local k = type(u) == "string" and C(S(v)):match(u)
	  if k then
	    expr[s-1] = tb[k](expr[s-1],expr[s+1])
	    table.remove(expr, s)
	    table.remove(expr, s)
	  end
	end
  end
  return expr[1]
end

print(eval{expression:match(io.read())})
Expr = {}
Expr.eval = 0

BinaryExpr = new Expr
BinaryExpr.eval = function()
	if self.op == "+" then return self.lhs.eval + self.rhs.eval
	if self.op == "-" then return self.lhs.eval - self.rhs.eval
	if self.op == "*" then return self.lhs.eval * self.rhs.eval
	if self.op == "/" then return self.lhs.eval / self.rhs.eval
end function
binop = function(lhs, op, rhs)
	e = new BinaryExpr
	e.lhs = lhs
	e.op = op
	e.rhs = rhs
	return e
end function

parseAtom = function(inp)
	tok = inp.pull
	if tok >= "0" and tok <= "9" then
		e = new Expr
		e.eval = val(tok)
		while inp and inp[0] >= "0" and inp[0] <= "9"
			e.eval = e.eval * 10 + val(inp.pull)
		end while
	else if tok == "(" then
		e = parseAddSub(inp)
		inp.pull // swallow closing ")"
		return e
	else	
		print "Unexpected token: " + tok
		exit
	end if
	return e	
end function

parseMultDiv = function(inp)
	next = @parseAtom
	e = next(inp)
	while inp and (inp[0] == "*" or inp[0] == "/")
		e = binop(e, inp.pull, next(inp))
	end while
	return e
end function

parseAddSub = function(inp)
	next = @parseMultDiv
	e = next(inp)
	while inp and (inp[0] == "+" or inp[0] == "-")
		e = binop(e, inp.pull, next(inp))
	end while
	return e
end function

while true
	s = input("Enter expression: ").replace(" ","")
	if not s then break
	inp = split(s, "")
	ast = parseAddSub(inp)
	print ast.eval
end while
Array concatenation
LuaMiniScript
a = {1, 2, 3}
b = {4, 5, 6}

for _, v in pairs(b) do
    table.insert(a, v)
end

print(table.concat(a, ", "))
arrOne = [1, 2, 3]
arrTwo = [4, 5, 6]
print arrOne + arrTwo
Array length
LuaMiniScript
-- For tables as simple arrays, use the # operator:
fruits = {"apple", "orange"}
print(#fruits)

-- Note the # symbol does not work for non-integer-indexed tables:
fruits = {fruit1 = "apple", fruit2 = "orange"}
print(#fruits)

-- For this you can use this short function:
function size (tab)
  local count = 0
  for k, v in pairs(tab) do
    count = count + 1
  end
  return count
end

print(size(fruits))
fruits = ["apple", "orange"]
print fruits.len
Arrays
LuaMiniScript
l = {}
l[1] = 1      -- Index starts with 1, not 0.
l[0] = 'zero' -- But you can use 0 if you want
l[10] = 2     -- Indexes need not be continuous
l.a = 3       -- Treated as l['a']. Any object can be used as index
l[l] = l      -- Again, any object can be used as an index. Even other tables
for i,v in next,l do print (i,v) end
arr = ["a", 1, 3]
print arr[0]

arr.push "x"
print arr.pop
Associative array/Creation
LuaMiniScript
hash = {}
hash[ "key-1" ] = "val1"
hash[ "key-2" ] = 1
hash[ "key-3" ] = {}
map = { 3: "test", "foo": 42 }

print map[3]
map[3] = "more tests"
print map[3]
print map["foo"]
print map.foo  // same as map["foo"] (only for string keys that are valid identifiers)
Associative array/Iteration
LuaMiniScript
local t = {
    ["foo"] = "bar",
    ["baz"] = 6,
    fortytwo = 7
}

for key,val in pairs(t) do
    print(string.format("%s: %s", key, val))
end
d = { 3: "test", "foo": 3 }

for keyVal in d
    print keyVal   // produces results like: { "key": 3, "value": "test" }
end for

for key in d.indexes
    print key
end for

for  val in d.values
    print val
end for
Associative array/Merging
LuaMiniScript
base = {name="Rocket Skates", price=12.75, color="yellow"}
update = {price=15.25, color="red", year=1974}

--[[ clone the base data ]]--
result = {}
for key,val in pairs(base) do
    result[key] = val
end

--[[ copy in the update data ]]--
for key,val in pairs(update) do
    result[key] = val
end

--[[ print the result ]]--
for key,val in pairs(result) do
    print(string.format("%s: %s", key, val))
end
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}

result = base + update

print result
Averages/Arithmetic mean
LuaMiniScript
function mean (numlist)
    if type(numlist) ~= 'table' then return numlist end
    num = 0
    table.foreach(numlist,function(i,v) num=num+v end)
    return num / #numlist
end

print (mean({3,1,4,1,5,9}))
arr = [ 1, 3, 7, 8, 9, 1 ]

avg = function(arr)
    avgNum = 0
    for num in arr
        avgNum = avgNum + num
    end for
    return avgNum / arr.len
end function

print avg(arr)
Averages/Median
LuaMiniScript
function median (numlist)
    if type(numlist) ~= 'table' then return numlist end
    table.sort(numlist)
    if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end
    return numlist[math.ceil(#numlist/2)]
end

print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2}))
list.median = function()
    self.sort
    m = floor(self.len/2)
    if self.len % 2 then return self[m]
    return (self[m] + self[m-1]) * 0.5
end function
    
print [41, 56, 72, 17, 93, 44, 32].median
print [41, 72, 17, 93, 44, 32].median
Averages/Simple moving average
LuaMiniScript
function sma(period)
	local t = {}
	function sum(a, ...)
		if a then return a+sum(...) else return 0 end
	end
	function average(n)
		if #t == period then table.remove(t, 1) end
		t[#t + 1] = n
		return sum(unpack(t)) / #t
	end
	return average
end

sma5 = sma(5)
sma10 = sma(10)
print("SMA 5")
for v=1,15 do print(sma5(v)) end
print("\nSMA 10")
for v=1,15 do print(sma10(v)) end
SMA = {}
SMA.P = 5  // (a default; may be overridden)
SMA.buffer = null
SMA.next = function(n)
    if self.buffer == null then self.buffer = []
    self.buffer.push n
    if self.buffer.len > self.P then self.buffer.pull
    return self.buffer.sum / self.buffer.len
end function

sma3 = new SMA
sma3.P = 3
sma5 = new SMA

for i in range(10)
    num = round(rnd*100)
    print "num: " + num + "  sma3: " + sma3.next(num) + "  sma5: " + sma5.next(num)
end for
Babbage problem
LuaMiniScript
-- get smallest number <= sqrt(269696)
k = math.floor(math.sqrt(269696))

-- if root is odd -> make it even
if k % 2 == 1 then
    k = k - 1
end

-- cycle through numbers
while not ((k * k) % 1000000 == 269696) do
    k = k + 2
end

io.write(string.format("%d * %d = %d\n", k, k, k * k))
// Lines that start with "//" are "comments" that are ignored
// by the computer.  We use them to explain the code.

// Start by finding the smallest number that could possibly
// square to 269696.  sqrt() returns the square root of a 
// number, and floor() truncates any fractional part.
k = floor(sqrt(269696))

// Since 269696 is even, we are only going to consider even
// roots.  We use the % (modulo) operator, which returns the
// remainder after division, to tell if k is odd; if so, we
// add 1 to make it even.
if k % 2 == 1 then k = k + 1

// Now we count up by 2 from k, until we find a number that,
// when squared, ends in 269696 (using % again).
while k^2 % 1000000 != 269696
    k = k + 2
end while

// The first such number we find is our answer.
print k + "^2 = " + k^2
Bacon cipher
LuaMiniScript
function Bacon( txt, secret, e )
    local alpha = {}
    function encode( txt, secret )
        function toAlpha( secret )
            local str, z = "", 0
            secret = secret:upper()
            for i = 1, string.len( secret ) do
                z = secret:sub( i, i )
                if z < 'A' or z > 'Z'  then
                    str = str .. alpha[27]
                else
                    k = z:byte( 1 ) - 65 + 1
                    str = str .. alpha[k]
                end
            end
            return str
        end

        local sec, encoded, idx = toAlpha( secret ), "", 0
        if sec:len() > txt:len() then
            print( "Text is too short!" )
           return
        end

        txt = txt:lower()
        for i = 1, string.len( sec ) do
            t = txt:sub( idx, idx )
            while( t < 'a' or t > 'z' ) do
                encoded = encoded .. t
                idx = idx + 1
                t = txt:sub( idx, idx )
            end

            idx = idx + 1
            if sec:sub( i, i ) == '1' then
                encoded = encoded .. string.char( t:byte(1) - 32 )
            else
                encoded = encoded .. t
            end
        end
        return encoded
    end

    function decode( txt )
        local secret, c = "", 0
        for i = 1, string.len( txt ) do
            c = txt:sub( i, i )
            if not( c < 'a' and ( c < 'A' or c > 'Z' ) or c > 'z' ) then
                local s = 0
                if c == c:upper() then s = 1 end
                secret = secret .. s
            end
        end

        function fromAlpha( secret )
            function find( a, arr )
                for i = 1, #arr do
                    if arr[i] == a then return i end
                end
                return -1
            end

            local l, msg, c, idx = secret:len(), "", 0, 0
            if math.fmod( l, 5 ) ~= 0 then
                print( "Message length does not match!" )
                return
            end
            for i = 1, l, 5 do
                c = secret:sub( i, i + 4 )
                idx = find( c, alpha )
                if idx > 0 then
                    if idx == 27 then
                        msg = msg .. " "  -- unknown char - add space
                    else
                        msg = msg .. string.char( 64 + idx )
                    end
                end
            end
            return msg
        end
        return fromAlpha( secret )
    end

    -- create alphabet
    for i = 0, 26 do
        local t, num = "", i
        for b = 5, 1, -1 do
            t =  math.fmod( num, 2 ) .. t
            num = math.floor( num / 2 )
        end
        alpha[#alpha + 1] = t
    end

    -- encode or decode
    if e == 1 then
        return encode( txt, secret )
    elseif e == 0 then
        return decode( secret )
    end
end

local a = Bacon( "Chase the pig around the house present belly, scratch hand when stroked. "..
                 "When in doubt, wash jump around on couch, meow constantly until given food, "..
                 "favor packaging over toy. And sometimes switches in french and say 'miaou' "..
                 "just because well why not has closed eyes but still sees you lick yarn hanging "..
                 "out of own butt so pelt around the house and up and down stairs chasing
phantoms.",
                 "Fall over dead, not really but gets sypathy", 1 )
print( a )
print( Bacon( "", a, 0 ) )
c = {}
c["a"] = "AAAAA"; c["b"] = "AAAAB"; c["c"] = "AAABA"; c["d"] = "AAABB"; c["e"] = "AABAA"; c["f"] =
"AABAB"; 
c["g"] = "AABBA"; c["h"] = "AABBB"; c["i"] = "ABAAA"; c["j"] = "ABAAB"; c["k"] = "ABABA"; c["l"] =
"ABABB"; 
c["m"] = "ABBAA"; c["n"] = "ABBAB"; c["o"] = "ABBBA"; c["p"] = "ABBBB"; c["q"] = "BAAAA"; c["r"] =
"BAAAB"; 
c["s"] = "BAABA"; c["t"] = "BAABB"; c["u"] = "BABAA"; c["v"] = "BABAB"; c["w"] = "BABBA"; c["x"] =
"BABBB"; 
c["y"] = "BBAAA"; c["z"] = "BBAAB"; c[" "] = "BBBAA";
codeMap = c  // (used "c" above just to make the lines shorter)
decodeMap = {}
for kv in codeMap
	decodeMap[kv.value] = kv.key
end for

message = "Computers are everywhere.  There are the obvious ones, like your smart phone or game
system. "
message = message + "There are less obvious ones, like in your microwave or your bedside clock.  And
then "
message = message + "there are the really invisible ones, like the 50 or so small computers in your
car."
message = message + "All these computers work in pretty much the same way."
message = message.values  // (convert to list)

encodeChar = function(ch)
	out = []
	for bit in codeMap[ch]
		while message[0].upper == message[0].lower
			out.push message.pull   // (not a letter we can use; pass through as-is)
		end while
		if bit == "A" then out.push message.pull.upper else out.push message.pull.lower
	end for
	return out
end function
	
encode = function(s)
	out = []
	for ch in s
		out = out + encodeChar(ch)
	end for
	return out.join("")
end function

decodeChar = function(encodedChar)
	code = ""
	for ch in encodedChar
		if ch == ch.upper then code = code + "A" else code = code + "B"
	end for
	if decodeMap.hasIndex(code) then return decodeMap[code]
	return "?"
end function

decode = function(s)
	// strip out all non-letters
	schars = s.values
	for i in range(schars.len-1, 0)
		if schars[i].lower == schars[i].upper then schars.remove i
	end for
	s = schars.join("")
	// now, decode using groups of 5 characters
	out = []
	for i in range(0, s.len-1, 5)
		out.push decodeChar(s[i:i+5])
	end for
	return out.join("")
end function

codedMsg = encode("the quick brown fox jumps over the lazy dog")
print codedMsg
print decode(codedMsg)
Balanced brackets
LuaMiniScript
function isBalanced(s)
  --Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters.
  --Any two characters can be used.
  return s:gsub('%b[]','')=='' and true or false
end

function randomString()
  math.randomseed(os.time())
  math.random()math.random()math.random()math.random()
  local tokens={'[',']'}
  local result={}
  for i=1,8 do
    table.insert(result,tokens[math.random(1,2)])
  end
  return table.concat(result)
end

local RS=randomString()
print(RS)
print(isBalanced(RS))
isBalanced = function(str) 
	level = 0
	for c in str
		if c == "[" then level = level + 1
		if c == "]" then level = level - 1
		if level < 0 then return false
	end for
	return level == 0
end function
Barnsley fern
LuaMiniScript
g = love.graphics
wid, hei = g.getWidth(), g.getHeight()

function choose( i, j ) 
  local r = math.random()
  if r < .01 then return 0, .16 * j 
    elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6
    elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44
    else return .85 * i + .04 * j, -.04 * i + .85 * j + 1.6
  end
end
function createFern( iterations )
  local hw, x, y, scale = wid / 2, 0, 0, 45
  local pts = {}
  for k = 1, iterations do
    pts[1] = { hw + x * scale, hei - 15 - y * scale, 
               20 + math.random( 80 ), 
               128 + math.random( 128 ), 
               20 + math.random( 80 ), 150 }
    g.points( pts )
    x, y = choose( x, y )
  end
end
function love.load()
  math.randomseed( os.time() )
  canvas = g.newCanvas( wid, hei )
  g.setCanvas( canvas )
  createFern( 15e4 )
  g.setCanvas()
end
function love.draw()
  g.draw( canvas )
end
clear
x = 0
y = 0
for i in range(100000)
	gfx.setPixel 300 + 58 * x, 58 * y, color.green
	roll = rnd * 100
	xp = x
	if roll < 1 then
		x = 0
		y = 0.16 * y
	else if roll < 86 then
		x = 0.85 * x + 0.04 * y
		y = -0.04 * xp + 0.85 * y + 1.6
	else if roll < 93 then
		x = 0.2 * x - 0.26 * y
		y = 0.23 * xp + 0.22 * y + 1.6
	else
		x = -0.15 * x + 0.28 * y
		y = 0.26 * xp + 0.24 * y + 0.44
	end if
end for
Binary digits
LuaMiniScript
function dec2bin (n)
    local bin = ""
    while n > 0 do
        bin = n % 2 .. bin
        n = math.floor(n / 2)
    end
    return bin
end

print(dec2bin(5))
print(dec2bin(50))
print(dec2bin(9000))
binary = function(n)
    result = ""
    while n
        result = str(n%2) + result
        n = floor(n/2)
    end while
    if not result then return "0"
    return result
end function
 
print binary(5)
print binary(50)
print binary(9000)
print binary(0)
Binary search
LuaMiniScript
function binarySearch (list,value)
    local low = 1
    local high = #list
    while low <= high do
        local mid = math.floor((low+high)/2)
        if list[mid] > value then high = mid - 1
        elseif list[mid] < value then low = mid + 1
        else return mid
        end
    end
    return false
end
binarySearch = function(A, value, low, high)
    if high < low then return null
    mid = floor((low + high) / 2)
    if A[mid] > value then return binarySearch(A, value, low, mid-1)
    if A[mid] < value then return binarySearch(A, value, mid+1, high)
    return mid
end function
Boolean values
LuaMiniScript
if 0 then print "0" end             -- This prints
if "" then print"empty string" end  -- This prints
if {} then print"empty table" end   -- This prints
if nil then print"this won't print" end
if true then print"true" end
if false then print"false" end      -- This does not print
boolTrue = true
boolFalse = false

if boolTrue then print "boolTrue is true, and its value is: " + boolTrue

if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse

mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue)
Bulls and cows
LuaMiniScript
function ShuffleArray(array)
   for i=1,#array-1 do
      local t = math.random(i, #array)
      array[i], array[t] = array[t], array[i]
   end
end

function GenerateNumber()
   local digits = {1,2,3,4,5,6,7,8,9}

   ShuffleArray(digits)

   return digits[1] * 1000 +
          digits[2] *  100 +
          digits[3] *   10 +
          digits[4]
end

function IsMalformed(input)
   local malformed = false

   if #input == 4 then
      local already_used = {}
      for i=1,4 do
         local digit = input:byte(i) - string.byte('0')
         if digit < 1 or digit > 9 or already_used[digit] then
            malformed = true
            break
         end
         already_used[digit] = true
      end
   else
      malformed = true
   end

   return malformed
end

math.randomseed(os.time())
math.randomseed(math.random(2^31-1)) -- since os.time() only returns seconds

print("\nWelcome to Bulls and Cows!")
print("")
print("The object of this game is to guess the random 4-digit number that the")
print("computer has chosen. The number is generated using only the digits 1-9,")
print("with no repeated digits. Each time you enter a guess, you will score one")
print("\"bull\" for each digit in your guess that matches the corresponding digit")
print("in the computer-generated number, and you will score one \"cow\" for each")
print("digit in your guess that appears in the computer-generated number, but is")
print("in the wrong position. Use this information to refine your guesses. When")
print("you guess the correct number, you win.");
print("")

quit = false

repeat
   magic_number = GenerateNumber()
   magic_string = tostring(magic_number) -- Easier to do scoring with a string
   repeat
      io.write("\nEnter your guess (or 'Q' to quit): ")
      user_input = io.read()
      if user_input == 'Q' or user_input == 'q' then
         quit = true
         break
      end

      if not IsMalformed(user_input) then
         if user_input == magic_string then
            print("YOU WIN!!!")
         else
            local bulls, cows = 0, 0
            for i=1,#user_input do
               local find_result = magic_string:find(user_input:sub(i,i))

               if find_result and find_result == i then
                  bulls = bulls + 1
               elseif find_result then
                  cows = cows + 1
               end
            end
            print(string.format("You scored %d bulls, %d cows", bulls, cows))
         end
      else
         print("Malformed input. You must enter a 4-digit number with")
         print("no repeated digits, using only the digits 1-9.")
      end

   until user_input == magic_string

   if not quit then
      io.write("\nPress <Enter> to play again or 'Q' to quit: ")
      user_input = io.read()
      if user_input == 'Q' or user_input == 'q' then
         quit = true
      end
   end

   if quit then
      print("\nGoodbye!")
   end
until quit
secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")

while true
    guess = input("Your guess? ").split("")
    if guess.len != 4 then
        print "Please enter 4 numbers, with no spaces."
        continue
    end if
    bulls = 0
    cows = 0
    for i in guess.indexes
        if secret[i] == guess[i] then
            bulls = bulls + 1
        else if secret.indexOf(guess[i]) != null then
            cows = cows + 1
        end if
    end for
    if bulls == 4 then
        print "You got it!  Great job!"
        break
    end if
    print "You score " + bulls + " bull" + "s"*(bulls!=1) + 
    " and " + cows + " cow" + "s"*(cows!=1) + "."
end while
Caesar cipher
LuaMiniScript
local function encrypt(text, key)
	return text:gsub("%a", function(t)
			local base = (t:lower() == t and string.byte('a') or string.byte('A'))

			local r = t:byte() - base
			r = r + key
			r = r%26 -- works correctly even if r is negative
			r = r + base
			return string.char(r)
		end)
end

local function decrypt(text, key)
	return encrypt(text, -key)
end

caesar = {
	encrypt = encrypt,
	decrypt = decrypt,
}

-- test
do
	local text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
	local encrypted = caesar.encrypt(text, 7)
	local decrypted = caesar.decrypt(encrypted, 7)
	print("Original text:  ", text)
	print("Encrypted text: ", encrypted)
	print("Decrypted text: ", decrypted)
end
caesar = function(s, key)
    chars = s.values
    for i in chars.indexes
        c = chars[i]
        if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+key)%26)
        if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+key)%26)
    end for
    return chars.join("")
end function

print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)
Call an object method
LuaMiniScript
local object = { name = "foo", func = function (self) print(self.name) end }

object:func() -- with : sugar
object.func(object) -- without : sugar
Dog = {}
Dog.name = ""
Dog.help = function()
    print "This class represents dogs."
end function
Dog.speak = function()
    print self.name + " says Woof!"
end function

fido = new Dog
fido.name = "Fido"

Dog.help    // calling a "class method"
fido.speak  // calling an "instance method"
Case-sensitivity of identifiers
LuaMiniScript
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"

print( "There are three dogs named "..dog..", "..Dog.." and "..DOG.."." )
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"

print "There are three dogs named " + dog + ", " + Dog + " and " + DOG
Classes
LuaMiniScript
myclass = setmetatable({
__index = function(z,i) return myclass[i] end, --this makes class variables a possibility
setvar = function(z, n) z.var = n end
}, {
__call = function(z,n) return setmetatable({var = n}, myclass) end
})

instance = myclass(3)

print(instance.var) -->3

instance:setvar(6)

print(instance.var) -->6
// MiniScript is prototype based
Weapon = { "name": "Sword", "damage": 3 }
Weapon.slice = function()
    print "Did " + self.damage + " damage with " + self.name
end function

wep = new Weapon  // Same as: wep = { "__isa": Weapon }

wep.name = "Lance"

wep.slice
Collections
LuaMiniScript
collection = {0, '1'}
print(collection[1]) -- prints 0

collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs
print(collection["foo"]) -- prints 0
print(collection.foo) -- syntactic sugar, also prints 0

collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}
seq = [0, "foo", pi]
seq.push 42
seq = seq + [1, 2, 3]
print seq
Compound data type
LuaMiniScript
a = {x = 1; y = 2}
b = {x = 3; y = 4}
c = {
    x = a.x + b.x;
    y = a.y + b.y
}
print(a.x, a.y)  --> 1 2
print(c.x, c.y)  --> 4 6
Point = {}
Point.x = 0
Point.y = 0
Conditional structures
LuaMiniScript
--if-then-elseif-then-else
if a then
  b()
elseif c then
  d()
else
  e()
end

for var = start, _end, step do --note: end is a reserved word
  something()
end

for var, var2, etc in iteratorfunction do
  something()
end

while somethingistrue() do
  something()
end

repeat
  something()
until somethingistrue()

cases = {
key1 = dothis,
key2 = dothat,
key3 = dotheother
}

cases[key]() --equivalent to dothis(), dothat(), or dotheother() respectively
x = 42
if x < 10 then
    print "small"
else if x < 20 then
    print "small-ish"
else if x > 100 then
    print "large"
else
    print "just right"
end if
Conway's Game of Life
LuaMiniScript
local function T2D(w,h) local t={} for y=1,h do t[y]={} for x=1,w do t[y][x]=0 end end return t end

local Life = {
  new = function(self,w,h)
    return setmetatable({ w=w, h=h, gen=1, curr=T2D(w,h), next=T2D(w,h)}, {__index=self})
  end,
  set = function(self, coords)
    for i = 1, #coords, 2 do
      self.curr[coords[i+1]][coords[i]] = 1
    end
  end,
  evolve = function(self)
    local curr, next = self.curr, self.next
    local ym1, y, yp1 = self.h-1, self.h, 1
    for i = 1, self.h do
      local xm1, x, xp1 = self.w-1, self.w, 1
      for j = 1, self.w do
        local sum = curr[ym1][xm1] + curr[ym1][x] + curr[ym1][xp1] +
                    curr[y][xm1] + curr[y][xp1] +
                    curr[yp1][xm1] + curr[yp1][x] + curr[yp1][xp1]
        next[y][x] = ((sum==2) and curr[y][x]) or ((sum==3) and 1) or 0
        xm1, x, xp1 = x, xp1, xp1+1
      end
      ym1, y, yp1 = y, yp1, yp1+1
    end
    self.curr, self.next, self.gen = self.next, self.curr, self.gen+1
  end,
  render = function(self)
    print("Generation "..self.gen..":")
    for y = 1, self.h do
      for x = 1, self.w do
        io.write(self.curr[y][x]==0 and "□ " or "■ ")
      end
      print()
    end
  end
}
// Conway's Game of Life
clear
rows = 64; rowRange = range(0, rows-1)
cols = 96; colRange = range(0, cols-1)
// prepare two tile displays, in display layers 4 and 5
img = Image.create(2, 1); img.setPixel 1, 0, color.white
grids = []
for dispIdx in [4,5]
	display(dispIdx).mode = displayMode.tile
	td = display(dispIdx)
	td.cellSize = 10  // size of cells on screen
	td.extent = [cols, rows]
	td.overlap = -1   // adds a small gap between cells
	td.tileSet = img; td.tileSetTileSize = 1
	td.clear 0
	grids.push td
end for

// initialize to a random state
for x in colRange
	for y in rowRange
		td.setCell x, y, rnd > 0.5
	end for
end for

curIdx = 5
// main loop
while true
	yield
	td = grids[curIdx-4]
	newIdx = 4 + (curIdx == 4)
	newTd = grids[newIdx-4]
	for x in colRange
		for y in rowRange
			// get sum of neighboring states
			sum = 0
			for i in [x-1, x, x+1]
				if i < 0 or i >= cols then continue
				for j in [y-1, y, y+1]
					if j < 0 or j >= rows then continue
					if i==x and j==y then continue
					sum = sum + td.cell(i,j)
				end for
			end for
			// Now, update the cell based on current state
			// and neighboring sum.
			if td.cell(x,y) then
				newTd.setCell x, y, (sum == 2 or sum == 3)
			else
				newTd.setCell x, y, sum == 3
			end if
		end for
	end for
	display(newIdx).mode = displayMode.tile
	display(curIdx).mode = displayMode.off
	curIdx = newIdx
end while
Copy a string
LuaMiniScript
a = "string"
b = a
print(a == b) -->true
print(b) -->string
phrase = "hi"
copy = phrase
print phrase
print copy
Count occurrences of a substring
LuaMiniScript
function countSubstring(s1, s2)
    return select(2, s1:gsub(s2, ""))
end

print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))
string.count = function(s)
    return self.split(s).len - 1
end function

print "the three truths".count("th")
print "ababababab".count("abab")
Cumulative standard deviation
LuaMiniScript
function stdev()
  local sum, sumsq, k = 0,0,0
  return function(n)
    sum, sumsq, k = sum + n, sumsq + n^2, k+1
    return math.sqrt((sumsq / k) - (sum/k)^2)
  end
end

ldev = stdev()
for i, v in ipairs{2,4,4,4,5,5,7,9} do
  print(ldev(v))
end
StdDeviator = {}
StdDeviator.count = 0
StdDeviator.sum = 0
StdDeviator.sumOfSquares = 0

StdDeviator.add = function(x)
    self.count = self.count + 1
    self.sum = self.sum + x
    self.sumOfSquares = self.sumOfSquares + x*x
end function

StdDeviator.stddev = function()
    m = self.sum / self.count
    return sqrt(self.sumOfSquares / self.count - m*m)
end function

sd = new StdDeviator
for x in [2, 4, 4, 4, 5, 5, 7, 9]
    sd.add x
end for
print sd.stddev
Determine if a string is numeric
LuaMiniScript
if tonumber(a) ~= nil then
   --it's a number
end;
isNumeric = function(s)
    return s == "0" or s == "-0" or val(s) != 0
end function

print isNumeric("0")
print isNumeric("42")
print isNumeric("-3.14157")
print isNumeric("5@*#!")
print isNumeric("spam")
Draw a clock
LuaMiniScript
==={{libheader|LÖVE}}===
Several nice clocks in the [http://love2d.org/forums/viewtopic.php?f=5&t=77346 LÖVE-forum]


// draw a clock hand, then copy it to an image
gfx.clear color.clear
gfx.fillPoly [[60,5], [64,10], [128,5], [64,0]], color.yellow
handImg = gfx.getImage(0,0, 128,10)

clear  // clear all displays

// prepare the face sprite
faceImg = file.loadImage("/sys/pics/shapes/CircleThinInv.png")
face = new Sprite
face.image = faceImg
face.scale = 2
face.x = 480; face.y = 320
display(4).sprites.push face

// prepare the hand sprite (from previously created image)
hand = new Sprite
hand.image = handImg
hand.x = face.x; hand.y = face.y
display(4).sprites.push hand

// main loop
while true
	hand.rotation = 90 - floor(time) % 60 * 6
	wait
end while
Entropy
LuaMiniScript
function log2 (x) return math.log(x) / math.log(2) end

function entropy (X)
    local N, count, sum, i = X:len(), {}, 0
    for char = 1, N do
        i = X:sub(char, char)
        if count[i] then
            count[i] = count[i] + 1
        else
            count[i] = 1
        end
    end
    for n_i, count_i in pairs(count) do
        sum = sum + count_i / N * log2(count_i / N)
    end
    return -sum
end

print(entropy("1223334444"))
entropy = function(s)
    count = {}
    for c in s
        if count.hasIndex(c) then count[c] = count[c]+1 else count[c] = 1
    end for
    sum = 0
    for x in count.values
        countOverN = x / s.len
        sum = sum + countOverN * log(countOverN, 2)
    end for
    return -sum
end function

print entropy("1223334444")
Even or odd
LuaMiniScript
-- test for even number
if n % 2 == 0 then
  print "The number is even"
end

-- test for odd number
if not (n % 2 == 0) then
  print "The number is odd"
end
for i in range(-4, 4)
    if i % 2 == 0 then print i + " is even" else print i + " is odd"
end for
Execute HQ9+
LuaMiniScript
function runCode( code )
    local acc, lc = 0
    for i = 1, #code do
        lc = code:sub( i, i ):upper()
        if lc == "Q" then print( lc )
        elseif lc == "H" then print( "Hello, World!" )
        elseif lc == "+" then acc = acc + 1
        elseif lc == "9" then
            for j = 99, 1, -1 do
                if j > 1 then
                    print( string.format( "%d bottles of beer on the wall\n%d bottles of beer\nTake
one down, pass it around\n%d bottles of beer on the wall\n", j, j, j - 1 ) )
                else
                    print( "1 bottle of beer on the wall\n1 bottle of beer\nTake one down and pass
it around\nno more bottles of beer on the wall\n\n"..
                           "No more bottles of beer on the wall\nNo more bottles of beer\n"..
                           "Go to the store and buy some more\n99 bottles of beer on the wall.\n" )
                end
            end
        end
    end
end
code = input("Enter HQ9+ program: ")

sing = function()
    for i in range(99,2)
        print i + " bottles of beer on the wall, " + i + " bottles of beer"
        print "Take one down, pass it around, " + (i-1) + " bottle" + "s"*(i>2) + " of beer on the
wall"
    end for
    print "1 bottle of beer on the wall, 1 bottle of beer"
    print "Take one down, pass it around, no bottles of beer on the wall!"
end function

accumulator = 0
for c in code
    c = c.lower
    if c == "h" then print "Hello World"
    if c == "q" then print code
    if c == "9" then sing
    if c == "+" then accumulator = accumulator + 1
end for
Factorial
LuaMiniScript
function fact(n)
  return n > 0 and n * fact(n-1) or 1
end
factorial = function(n)
    result = 1
    for i in range(2,n)
        result = result * i
    end for
    return result
end function

print factorial(10)
Factors of an integer
LuaMiniScript
function Factors( n ) 
    local f = {}
    
    for i = 1, n/2 do
        if n % i == 0 then 
            f[#f+1] = i
        end
    end
    f[#f+1] = n
    
    return f
end
factors = function(n)
    result = [1]
    for i in range(2, n)
        if n % i == 0 then result.push i
    end for
    return result
end function

while true
    n = val(input("Number to factor (0 to quit)? "))
    if n <= 0 then break
    print factors(n)
end while
Fibonacci sequence
LuaMiniScript
--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n) 
  return n < 2 and n or fibs(n - 1) + fibs(n - 2) 
end
fibonacci = function(n)
    if n < 2 then return n
    n1 = 0
    n2 = 1
    for i in range(n-1, 1)
        ans = n1 + n2
        n1 = n2
        n2 = ans
    end for
    return ans
end function

print fibonacci(6)
Filter
LuaMiniScript
function filter(t, func)
  local ret = {}
  for i, v in ipairs(t) do
    ret[#ret+1] = func(v) and v or nil
  end
  return ret
end

function even(a) return a % 2 == 0 end

print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even)))
list.filter = function(f)
    result = []
    for item in self
        if f(item) then result.push item
    end for
    return result
end function

isEven = function(x)
    return x % 2 == 0
end function

nums = [1, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 21]
print nums.filter(@isEven)
FizzBuzz
LuaMiniScript
for i = 1, 100 do
	if i % 15 == 0 then
		print("FizzBuzz")
	elseif i % 3 == 0 then
		print("Fizz")
	elseif i % 5 == 0 then
		print("Buzz")
	else
		print(i)
	end
end
for i in range(1,100)
    if i % 15 == 0 then
        print "FizzBuzz"
    else if i % 3 == 0 then
        print "Fizz"
    else if i % 5 == 0 then
        print "Buzz"
    else
        print i
    end if
end for
Flipping bits game
LuaMiniScript
target, board, moves, W, H = {}, {}, 0, 3, 3

function getIndex( i, j ) return i + j * W - W end

function flip( d, r )
    function invert( a ) if a == 1 then return 0 end return 1 end
    local idx
    if d == 1 then
        for i = 1, W do
            idx = getIndex( i, r )
            board[idx] = invert( board[idx] )
        end
    else
        for i = 1, H do
            idx = getIndex( r, i )
            board[idx] = invert( board[idx] )
        end
    end
    moves = moves + 1
end
function createTarget()
    target, board = {}, {}
    local idx
    for j = 1, H do
        for i = 1, W do
            idx = getIndex( i, j )
            if math.random() < .5 then target[idx] = 0
            else target[idx] = 1
            end
            board[idx] = target[idx]
        end
    end
    for i = 1, 103 do
        if math.random() < .5 then flip( 1, math.random( H ) )
        else flip( 2, math.random( W ) )
        end
    end
    moves = 0
end
function getUserInput()
    io.write( "Input row and/or column: " ); local r = io.read()
    local a
    for i = 1, #r do
        a = string.byte( r:sub( i, i ):lower() )
        if a >= 48 and a <= 57 then flip( 2, a - 48 ) end
        if a >= 97 and a <= string.byte( 'z' ) then flip( 1, a - 96 ) end
    end
end
function solved()
    local idx
    for j = 1, H do
        for i = 1, W do
            idx = getIndex( i, j )
            if target[idx] ~= board[idx] then return false end
        end
    end
    return true
end
function display()
    local idx
    io.write( "\nTARGET\n   " )
    for i = 1, W do io.write( string.format( "%d  ", i ) ) end; print()
    for j = 1, H do
        io.write( string.format( "%s  ", string.char( 96 + j ) ) )
        for i = 1, W do
            idx = getIndex( i, j )
            io.write( string.format( "%d  ", target[idx] ) )
        end; io.write( "\n" )
    end
    io.write( "\nBOARD\n   " )
    for i = 1, W do io.write( string.format( "%d  ", i ) ) end; print()
    for j = 1, H do
        io.write( string.format( "%s  ", string.char( 96 + j ) ) )
        for i = 1, W do
            idx = getIndex( i, j )
            io.write( string.format( "%d  ", board[idx] ) )
        end; io.write( "\n" )
    end
    io.write( string.format( "Moves: %d\n", moves ) )
end
function play()
    while true do
        createTarget()
        repeat
            display()
            getUserInput()
        until solved()
        display()
        io.write( "Very well!\nPlay again(Y/N)? " );
        if io.read():lower() ~= "y" then return end
    end
end
--[[entry point]]--
math.randomseed( os.time() )
play()
// Flipping Bits game.
// Transform a start grid to an end grid by flipping rows or columns.

size = 3

board = []
goal = []
for i in range(1,size)
    row = []
    for j in range(1,size)
        row.push (rnd > 0.5)
    end for
    board.push row
    goal.push row[0:]
end for

flipRow = function(n)
    for j in range(0, size-1)
        board[n-1][j] = not board[n-1][j]
    end for
end function

flipCol = function(n)
    for i in range(0, size-1)
        board[i][n-1] = not board[i][n-1]
    end for
end function

flipAny = function(s)
    s = s[0].upper
    if s >= "A" then flipCol s.code - 64 else flipRow val(s)
end function

for scramble in range(20)
    if rnd < 0.5 then flipRow ceil(rnd*size) else flipCol ceil(rnd*size)
end for

solved = function()
    for i in range(0, size-1)
        for j in range(0, size-1)
            if board[i][j] != goal[i][j] then return false
        end for
    end for
    return true
end function

moveCount = 0
while true
    print "  CURRENT:" + " "*(4+size*3) + "GOAL:"
    for i in range(1,size)
        s = i + " " + str(board[i-1])
        s = s + " "*(3+size*3) + str(goal[i-1])
        print s
    end for
    s = "   "
    for i in range(1,size)
        s = s + char(64+i) + "  "
    end for
    print s
    if solved then break
    moveCount = moveCount + 1
    inp = input("Move " + moveCount + "? ")
    flipAny(inp)
end while
print "You did it!"
Function composition
LuaMiniScript
function compose(f, g) return function(...) return f(g(...)) end end
funcA = function(x)
    return x * 10
end function

funcB = function(x)
    return x + 5
end function

compose = function(f, g)
    return function(x)
        return f(g(x))
    end function
end function

f = compose(@funcA, @funcB)
print f(3)  // should be equal to (3+5)*10
Function definition
LuaMiniScript
function multiply( a, b )
    return a * b
end
multiply = function(x,y)
    return x*y
end function

print multiply(6, 7)
General FizzBuzz
LuaMiniScript
function genFizz (param)
  local response
  print("\n")
  for n = 1, param.limit do
    response = ""
    for i = 1, 3 do
      if n % param.factor[i] == 0 then
        response = response .. param.word[i]
      end
    end
    if response == "" then print(n) else print(response) end
  end
end

local param = {factor = {}, word = {}}
param.limit = io.read()
for i = 1, 3 do
  param.factor[i], param.word[i] = io.read("*number", "*line")
end
genFizz(param)
factorWords = {}

maxNr = val(input("Max number? "))

while true
	factorInput = input("Factor? ")
	if factorInput == "" then break
	// Split input
	parts = factorInput.split(" ")
	factor = val(parts[0])
	word = parts[1]
	// Assign factor/word
	factorWords[factor] = word
end while

for nr in range(1,maxNr)
	matchingWords = ""
	for factor in factorWords.indexes
		if nr % factor == 0 then 
			matchingWords = matchingWords + factorWords[factor]
		end if
	end for
	if matchingWords then print matchingWords else print nr
end for
Generate Chess960 starting position
LuaMiniScript
-- Insert 'str' into 't' at a random position from 'left' to 'right'
function randomInsert (t, str, left, right)
    local pos
    repeat pos = math.random(left, right) until not t[pos]
    t[pos] = str
    return pos
end

-- Generate a random Chess960 start position for white major pieces
function chess960 ()
    local t, b1, b2 = {}
    local kingPos = randomInsert(t, "K", 2, 7)
    randomInsert(t, "R", 1, kingPos - 1)
    randomInsert(t, "R", kingPos + 1, 8)
    b1 = randomInsert(t, "B", 1, 8)
    b2 = randomInsert(t, "B", 1, 8)
    while (b2 - b1) % 2 == 0 do
        t[b2] = false
        b2 = randomInsert(t, "B", 1, 8)
    end
    randomInsert(t, "Q", 1, 8)
    randomInsert(t, "N", 1, 8)
    randomInsert(t, "N", 1, 8)
    return t
end

-- Main procedure
math.randomseed(os.time())
print(table.concat(chess960()))
// placeholder knights
rank = ["♘"] * 8

// function to get a random free space from a to b, inclusive
randFree = function(a, b)
    free = []
    for i in range(a, b)
        if rank[i] == "♘" then free.push i
    end for
    return free[rnd * free.len]
end function

// place the king
kingIdx = randFree(1, 6)
rank[kingIdx] = "♔"

// place rooks
rank[randFree(0, kingIdx - 1)] = "♖"
rank[randFree(kingIdx + 1, 7)] = "♖"

// place bishops
bishIdx = randFree(0, 7)
rank[bishIdx] = "♗"
while true
    i = randFree(0, 7)
    if i % 2 != bishIdx % 2 then break
end while
rank[i] = "♗"

// place queen
rank[randFree(0, 7)] = "♕"

print join(rank, " ")
Generate lower case ASCII alphabet
LuaMiniScript
function getAlphabet ()
    local letters = {}
    for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end
    return letters
end

local alpha = getAlphabet()
print(alpha[25] .. alpha[1] .. alpha[25]) 
letters = []
for i in range(code("a"), code("z"))
    letters.push char(i)
end for

print letters
Generic swap
LuaMiniScript
x, y = y, x                -- swap the values inside x and y
t[1], t[2] = t[2], t[1]    -- swap the first and second values inside table t
swap = function(map, a, b)
    temp = map[a]
    map[a] = map[b]
    map[b] = temp
end function

x = 1
y = 2
print "BEFORE: x=" + x + ", y=" + y
swap(locals, "x", "y")
print "AFTER:  x=" + x + ", y=" + y
Greatest common divisor
LuaMiniScript
function gcd(a,b)
	if b ~= 0 then
		return gcd(b, a % b)
	else
		return math.abs(a)
	end
end

function demo(a,b)
	print("GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b))
end

demo(100, 5)
demo(5, 100)
demo(7, 23)
gcd = function(a, b)
    while b
        temp = b
        b = a % b
        a = temp
    end while
    return abs(a)
end function

print gcd(18,12)
Greatest element of a list
LuaMiniScript
-- Table to store values
local values = {}
-- Read in the first number from stdin
local new_val = io.read"*n"
-- Append all numbers passed in
-- until there are no more numbers (io.read'*n' = nil) 
while new_val do
  values[#values+1] = new_val
  new_val = io.read"*n"
end

-- Print the max
print(math.max(unpack(values)))
list.max = function()
    if not self then return null
    result = self[0]
    for item in self
        if item > result then result = item
    end for
    return result
end function

print [47, 11, 42, 102, 13].max
Guess the number
LuaMiniScript
math.randomseed( os.time() )
n = math.random( 1, 10 )

print( "I'm thinking of a number between 1 and 10. Try to guess it: " )

repeat
    x = tonumber( io.read() )

    if x == n then
	print "Well guessed!"
    else
	print "Guess again: "
    end
until x == n
num = ceil(rnd*10)
while true
    x = val(input("Your guess?"))
    if x == num then
        print "Well guessed!"
        break
    end if
end while
Happy numbers
LuaMiniScript
function digits(n)
  if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
function sumsq(a, ...)
  return a and a ^ 2 + sumsq(...) or 0
end
local happy = setmetatable({true, false, false, false}, {
      __index = function(self, n)
         self[n] = self[sumsq(digits(n))]
         return self[n]
      end } )
i, j = 0, 1
repeat
   i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8
isHappy = function(x)
    while true
        if x == 89 then return false
        sum = 0
        while x > 0
            sum = sum + (x % 10)^2
            x = floor(x / 10)
        end while
        if sum == 1 then return true
        x = sum
    end while
end function

found = []
i = 1
while found.len < 8
    if isHappy(i) then found.push i
    i = i + 1
end while
print "First 8 happy numbers: " + found
Hash from two arrays
LuaMiniScript
function(keys,values)
  local t = {}
  for i=1, #keys do
    t[keys[i]] = values[i]
  end
end
keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]

d = {}
for i in range(keys.len-1)
    d[keys[i]] = values[i]
end for

print d
Hello world/Newbie
LuaMiniScript
io.write("Hello world, from ",_VERSION,"!\n")
print "Hello World!"
Hello world/Text
LuaMiniScript
print "Hello world!"
print "Hello world!"
Idiomatically determine all the lowercase and uppercase letters
LuaMiniScript
function ASCIIstring (pattern)
    local matchString, ch = ""
    for charNum = 0, 255 do
        ch = string.char(charNum)
        if string.match(ch, pattern) then
            matchString = matchString .. ch
        end
    end
    return matchString
end

print(ASCIIstring("%l"))
print(ASCIIstring("%u"))
toChars = function(seq)
    for i in seq.indexes
        seq[i] = char(seq[i])
    end for
    return seq.join("")
end function

print toChars(range(code("a"), code("z")))
print toChars(range(code("A"), code("Z")))
Infinity
LuaMiniScript
function infinity()
  return 1/0 --lua uses unboxed C floats for all numbers
end
posInfinity = 1/0
print posInfinity
Integer comparison
LuaMiniScript
print('Enter the first number: ')
a = tonumber(io.stdin:read())
print('Enter the second number: ')
b = tonumber(io.stdin:read())

if a < b then print(a .. " is less than " .. b) end
if a > b then print(a .. " is greater than " .. b) end
if a == b then print(a .. " is equal to " .. b) end
integer1 = input("Please Input Integer 1:").val
integer2 = input("Please Input Integer 2:").val
if integer1 < integer2 then print integer1 + " is less than " + integer2
if integer1 == integer2 then print integer1 + " is equal to " + integer2
if integer1 > integer2 then print integer1 + " is greater than " + integer2
Leap year
LuaMiniScript
function isLeapYear(year)
  return year%4==0 and (year%100~=0 or year%400==0)
end
isLeapYear = function(year)
  return year%4==0 and (year % 100 or not year % 400)
end function
Least common multiple
LuaMiniScript
function gcd( m, n )
    while n ~= 0 do
        local q = m
        m = n
        n = q % n
    end
    return m
end

function lcm( m, n )
    return ( m ~= 0 and n ~= 0 ) and m * n / gcd( m, n ) or 0
end

print( lcm(12,18) )
gcd = function(a, b)
    while b
        temp = b
        b = a % b
        a = temp
    end while
    return abs(a)
end function

lcm = function(a,b)
    if not a and not b then return 0
    return abs(a * b) / gcd(a, b)
end function

print lcm(18,12)
Levenshtein distance
LuaMiniScript
function leven(s,t)
    if s == '' then return t:len() end
    if t == '' then return s:len() end

    local s1 = s:sub(2, -1)
    local t1 = t:sub(2, -1)

    if s:sub(0, 1) == t:sub(0, 1) then
        return leven(s1, t1)
    end

    return 1 + math.min(
        leven(s1, t1),
        leven(s,  t1),
        leven(s1, t )
      )
end

print(leven("kitten", "sitting"))
print(leven("rosettacode", "raisethysword"))
import "stringUtil"
print "kitten".editDistance("sitting")
Longest common prefix
LuaMiniScript
function lcp (strList)
    local shortest, prefix, first = math.huge, ""
    for _, str in pairs(strList) do
        if str:len() < shortest then shortest = str:len() end
    end
    for strPos = 1, shortest do
        if strList[1] then
            first = strList[1]:sub(strPos, strPos)
        else
            return prefix
        end
        for listPos = 2, #strList do
            if strList[listPos]:sub(strPos, strPos) ~= first then
                return prefix
            end
        end
        prefix = prefix .. first
    end
    return prefix
end

local testCases, pre = {
    {"interspecies", "interstellar", "interstate"},
    {"throne", "throne"},
    {"throne", "dungeon"},
    {"throne", "", "throne"},
    {"cheese"},
    {""},
    {nil},
    {"prefix", "suffix"},
    {"foo", "foobar"}
}
for _, stringList in pairs(testCases) do
    pre = lcp(stringList)
    if pre == "" then print(string.char(238)) else print(pre) end
end
lcp = function(strList)
    if not strList then return null
    // find the shortest and longest strings (without sorting!)
    shortest = strList[0]
    longest = strList[0]
    for s in strList
        if s.len < shortest.len then shortest = s
        if s.len > longest.len then longest = s
    end for
    if shortest.len < 1 then return ""
    // now find how much of the shortest matches the longest
    for i in range(0, shortest.len-1)
        if shortest[i] != longest[i] then return shortest[:i]
    end for
    return shortest
end function

print lcp(["interspecies","interstellar","interstate"])
print lcp(["throne","throne"])
print lcp(["throne","dungeon"])
print lcp(["throne", "", "throne"])
print lcp(["cheese"])
print lcp([])
print lcp(["foo","foobar"])
Look-and-say sequence
LuaMiniScript
--returns an iterator over the first n copies of the look-and-say sequence
function lookandsayseq(n)
  local t = {1}
  return function()
    local ret = {}
    for i, v in ipairs(t) do
      if t[i-1] and v == t[i-1] then
        ret[#ret - 1] = ret[#ret - 1] + 1
      else
        ret[#ret + 1] = 1
        ret[#ret + 1] = v
      end
    end
    t = ret
    n = n - 1
    if n > 0 then return table.concat(ret) end
  end
end
for i in lookandsayseq(10) do print(i) end
// Look and Say Sequence
repeats = function(digit, string)
	count = 0
	for c in string
		if c != digit then break
		count = count + 1
	end for
	return str(count)
end function
 
numbers = "1"
print numbers
for i in range(1,10) // warning, loop size > 15 gets long numbers very quickly
	number = ""
	position = 0
	while position < numbers.len
		repeatCount = repeats(numbers[position], numbers[position:])
		number = number + repeatCount + numbers[position]
		position = position + repeatCount.val
	end while
	print number
	numbers = number
end for
Loops/Downward for
LuaMiniScript
for i=10,0,-1 do
  print(i)
end
for i in range(10, 0)
    print i
end for
Loops/For
LuaMiniScript
for i=1,5 do
  for j=1,i do
    io.write("*")
  end
  io.write("\n")
end
for i in range(1,5)
    s = ""
    for j in range(1, i)
        s = s + "*"
    end for
    print s
end for
Loops/For with a specified step
LuaMiniScript
for i=2,9,2 do
  print(i)
end
for i in range(1,20,4)
    print i
end for
Loops/Foreach
LuaMiniScript
t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do                       
  print(value, key)
end
for i in collection
   print i
end
Loops/While
LuaMiniScript
n = 1024
while n>0 do
  print(n)
  n = math.floor(n/2)
end
i = 1024
while i > 0
    print i
    i = floor(i/2)
end while
Luhn test of credit card numbers
LuaMiniScript
function luhn(n)
  n=string.reverse(n)
  print(n)
  local s1=0
  --sum odd digits
  for i=1,n:len(),2 do
    s1=s1+n:sub(i,i)
  end
  --evens
  local s2=0
  for i=2,n:len(),2 do
    local doubled=n:sub(i,i)*2
    doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end)
    s2=s2+doubled
  end
  print(s1)
  print(s2)
  local total=s1+s2
  if total%10==0 then
    return true
  end
  return false
end 

-- Note that this function takes strings, not numbers.
-- 16-digit numbers tend to be problematic
-- when looking at individual digits.
print(luhn'49927398716')
print(luhn'49927398717')
print(luhn'1234567812345678')
print(luhn'1234567812345670')
isValid = function(s)
    sum = 0
    odd = true
    for i in range(s.len-1)
        d = val(s[i])
        sum = sum + d * (2 - odd)
        if not odd and d > 4 then sum = sum - 9
        odd = not odd
    end for
    return sum % 10 == 0
end function

test = function(s)
    if isValid(s) then print s + ": valid" else print s + ": invalid"
end function

test "49927398716"
test "49927398717"
test "1234567812345678"
test "1234567812345670"
Magic 8-ball
LuaMiniScript
math.randomseed(os.time())
answers = {
  "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on
it.",
  "As I see it, yes.", "Most likely.", "Outlook good.", "Signs point to yes.", "Yes.",
  "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.",
"Concentrate and ask again.",
  "Don't bet on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very
doubtful."
}
while true do
  io.write("Q:  ")
  question = io.read()
  print("A:  "..answers[math.random(#answers)])
end
answers = ["It is certain", "It is decidedly so", "Without a doubt",
        "Yes, definitely", "You may rely on it", "As I see it, yes",
        "Most likely", "Outlook good", "Signs point to yes", "Yes",
        "Reply hazy, try again", "Ask again later",
        "Better not tell you now", "Cannot predict now",
        "Concentrate and ask again", "Don't bet on it",
        "My reply is no", "My sources say no", "Outlook not so good",
        "Very doubtful"]
print "Ask your question and the Magic 8 Ball will give you the answer!"
input "What is your question?"
print answers[rnd * answers.len]
Mandelbrot set
LuaMiniScript
local maxIterations = 250
local minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5
local miX, mxX, miY, mxY
function remap( x, t1, t2, s1, s2 )
    local f = ( x - t1 ) / ( t2 - t1 )
    local g = f * ( s2 - s1 ) + s1
    return g;
end
function drawMandelbrot()
    local pts, a, as, za, b, bs, zb, cnt, clr = {}
    for j = 0, hei - 1 do
        for i = 0, wid - 1 do
            a = remap( i, 0, wid, minX, maxX )
            b = remap( j, 0, hei, minY, maxY )
            cnt = 0; za = a; zb = b
            while( cnt < maxIterations ) do
                as = a * a - b * b; bs = 2 * a * b
                a = za + as; b = zb + bs
                if math.abs( a ) + math.abs( b ) > 16 then break end
                cnt = cnt + 1
            end
            if cnt == maxIterations then clr = 0
            else clr = remap( cnt, 0, maxIterations, 0, 255 )
            end
            pts[1] = { i, j, clr, clr, 0, 255 }
            love.graphics.points( pts )
        end
    end
end
function startFractal()
    love.graphics.setCanvas( canvas ); love.graphics.clear()
    love.graphics.setColor( 255, 255, 255 )
    drawMandelbrot(); love.graphics.setCanvas()
end
function love.load()
    wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
    canvas = love.graphics.newCanvas( wid, hei )
    startFractal()
end
function love.mousepressed( x, y, button, istouch )
    if button ==  1 then
        startDrag = true; miX = x; miY = y
    else
        minX = -2.5; maxX = 2.5; minY = minX; maxY = maxX
        startFractal()
        startDrag = false
    end
end
function love.mousereleased( x, y, button, istouch )
    if startDrag then
        local l
        if x > miX then mxX = x
        else l = x; mxX = miX; miX = l
        end
        if y > miY then mxY = y
        else l = y; mxY = miY; miY = l
        end
        miX = remap( miX, 0, wid, minX, maxX ) 
        mxX = remap( mxX, 0, wid, minX, maxX )
        miY = remap( miY, 0, hei, minY, maxY ) 
        mxY = remap( mxY, 0, hei, minY, maxY )
        minX = miX; maxX = mxX; minY = miY; maxY = mxY
        startFractal()
    end
end
function love.draw()
    love.graphics.draw( canvas )
end
ZOOM = 100
MAX_ITER = 40
gfx.clear color.black
for y in range(0,200)
	for x in range(0,300)
		zx = 0
		zy = 0
		cx = (x - 200) / ZOOM
		cy = (y - 100) / ZOOM
		for iter in range(MAX_ITER)
			if zx*zx + zy*zy > 4 then break
			tmp = zx * zx - zy * zy + cx
			zy = 2 * zx * zy + cy
			zx = tmp
		end for
		if iter then
			gfx.setPixel x, y, rgb(255-iter*6, 0, iter*6)
		end if
	end for
end for
Middle three digits
LuaMiniScript
function middle_three(n)
	if n < 0 then
		n = -n
	end
		
	n = tostring(n)
	if #n % 2 == 0 then
		return "Error: the number of digits is even."
	elseif #n < 3 then
		return "Error: the number has less than 3 digits."
	end

	local l = math.floor(#n/2)
	return n:sub(l, l+2)
end

-- test
do
	local t = {123, 12345, 1234567, 987654321,
	10001, -10001, -123, -100, 100, -12345, 1,
	2, -1, -10, 2002, -2002, 0}

	for _,n in pairs(t) do
		print(n, middle_three(n))	
	end
end
middle3 = function(num)
    if num < 0 then num = -num
    s = str(num)
    if s.len < 3 then return "Input too short"
    if s.len % 2 == 0 then return "Input length not odd"
    mid = (s.len + 1) / 2 - 1
    return s[mid-1:mid+2]
end function

for test in [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
    print test + " --> " + middle3(test)
end for
Multisplit
LuaMiniScript
--[[
Returns a table of substrings by splitting the given string on 
occurrences of the given character delimiters, which may be specified 
as a single- or multi-character string or a table of such strings.
If chars is omitted, it defaults to the set of all space characters, 
and keep is taken to be false. The limit and keep arguments are 
optional: they are a maximum size for the result and a flag 
determining whether empty fields should be kept in the result.
]]
function split (str, chars, limit, keep)
    local limit, splitTable, entry, pos, match = limit or 0, {}, "", 1
    if keep == nil then keep = true end
    if not chars then
        for e in string.gmatch(str, "%S+") do
                table.insert(splitTable, e)
        end
        return splitTable
    end
    while pos <= str:len() do
        match = nil
        if type(chars) == "table" then
            for _, delim in pairs(chars) do
                if str:sub(pos, pos + delim:len() - 1) == delim then
                    match = string.len(delim) - 1
                    break
                end
            end
        elseif str:sub(pos, pos + chars:len() - 1) == chars then
            match = string.len(chars) - 1
        end
        if match then
            if not (keep == false and entry == "") then
                table.insert(splitTable, entry)
                if #splitTable == limit then return splitTable end
                entry = ""
            end
        else
            entry = entry .. str:sub(pos, pos)
        end
        pos = pos + 1 + (match or 0)
    end
    if entry ~= "" then table.insert(splitTable, entry) end
    return splitTable
end

local multisplit = split("a!===b=!=c", {"==", "!=", "="})

-- Returned result is a table (key/value pairs) - display all entries
print("Key\tValue")
print("---\t-----")
for k, v in pairs(multisplit) do
    print(k, v)
end
parseSep = function(s, pats)
    result = []
    startPos = 0
    pos = 0
    while pos < s.len
        for pat in pats
            if s[pos : pos+pat.len] != pat then continue
            result.push s[startPos : pos]
            result.push "{" + pat + "}"
            startPos = pos + pat.len
            pos = startPos - 1
            break
        end for
        pos = pos + 1
    end while
    return result
end function

print parseSep("a!===b=!=c", ["==", "!=", "="])
Munching squares
LuaMiniScript
local clr =  {}
function drawMSquares()
	local points = {}
	for y = 0, hei-1 do
		for x = 0, wid-1 do
			local idx = bit.bxor(x, y)%256
			local r, g, b = clr[idx][1], clr[idx][2], clr[idx][3]
			local point = {x+1, y+1, r/255, g/255, b/255, 1}
			table.insert (points, point)
		end
	end
	love.graphics.points(points)
end

function createPalette()
	for i = 0, 255 do
		clr[i] = {i*2.8%256, i*3.2%256, i*1.5%256}
	end
end

function love.load()
	wid, hei = 256, 256
	love.window.setMode(wid, hei)
	canvas = love.graphics.newCanvas()
	love.graphics.setCanvas(canvas)
		createPalette()
		drawMSquares()
	love.graphics.setCanvas()
end

function love.draw()
	love.graphics.setColor(1,1,1)
	love.graphics.draw(canvas)
end
xor = function(a, b)
	result = 0
	bit = 1
	while a > 0 or b > 0
		if (a%2 == 0) != (b%2 == 0) then result = result + bit
		bit = bit * 2
		a = floor(a/2)
		b = floor(b/2)
	end while
	return result
end function

for x in range(0,255)
	for y in range(0,255)
		gfx.setPixel x, y, color.rgb(0, xor(x,y), 0)
	end for
end for
Mutual recursion
LuaMiniScript
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end
f = function(n)
    if n > 0 then return n - m(f(n - 1))
    return 1
end function

m = function(n)
    if n > 0 then return n - f(m(n - 1))
    return 0
end function

print f(12)
print m(12)
N'th
LuaMiniScript
function getSuffix (n)
    local lastTwo, lastOne = n % 100, n % 10
    if lastTwo > 3 and lastTwo < 21 then return "th" end
    if lastOne == 1 then return "st" end
    if lastOne == 2 then return "nd" end
    if lastOne == 3 then return "rd" end
    return "th"
end
 
function Nth (n) return n .. "'" .. getSuffix(n) end
 
for i = 0, 25 do print(Nth(i), Nth(i + 250), Nth(i + 1000)) end
ordinal = function(n)
    if n > 3 and n < 20 then return n + "th"
    if n % 10 == 1 then return n + "st"
    if n % 10 == 2 then return n + "nd"
    if n % 10 == 3 then return n + "rd"
    return n + "th"
end function

out = []
test = function(from, to)
    for i in range(from, to)
        out.push ordinal(i)
    end for
end function

test 0, 25
test 250, 265
test 1000, 1025
print out.join
Nested function
LuaMiniScript
function makeList (separator)
    local counter = 0
    local function makeItem(item)
            counter = counter + 1
            return counter .. separator .. item .. "\n"
        end
    return makeItem("first") .. makeItem("second") .. makeItem("third")
end
 
print(makeList(". "))
makeList = function(sep)
    counter = 0
    makeItem = function(item)
        outer.counter = counter + 1
        return counter + sep + item
    end function
    return [makeItem("first"), makeItem("second"), makeItem("third")]
end function
 
print makeList(". ")
Nim game
LuaMiniScript
tokens = 12

print("Nim Game\n")
print("Starting with " .. tokens .. " tokens.\n\n")

function printRemaining()
	print(tokens .. " tokens remaining.\n")
end

function playerTurn(take)
	take = math.floor(take)
	if (take < 1 or take > 3) then
		print ("\nTake must be between 1 and 3.\n")
		return false
	end
	
	tokens = tokens - take
	
	print ("\nPlayer takes " .. take .. " tokens.")
	printRemaining()
	return true
end

function computerTurn()
	take = tokens % 4
	tokens = tokens - take
	
	print("Computer takes " .. take .. " tokens.")
	printRemaining()
end

while (tokens > 0) do
	io.write("How many tokens would you like to take?: ")
	if playerTurn(io.read("*n")) then
		computerTurn()
	end
end

print ("Computer wins.")
tokens = 12
 
print "Nim Game"
print "Starting with " + tokens + " tokens."
print
 
printRemaining = function()
	print tokens + " tokens remaining."
	print
end function
 
playerTurn = function(take)
	take = floor(val(take))
	if take < 1 or take > 3 then
		print "Take must be between 1 and 3."
		return false
	end if
 
	globals.tokens = tokens - take
 
	print "Player takes " + take + " tokens."
	printRemaining
	return true
end function
 
computerTurn = function()
	take = tokens % 4
	globals.tokens = tokens - take
 
	print "Computer takes " + take + " tokens."
	printRemaining
end function
 
while tokens > 0
	if playerTurn(input("How many tokens would you like to take? ")) then
		computerTurn
	end if
end while
 
print "Computer wins."
Number names
LuaMiniScript
words = {"one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine "}
levels = {"thousand ", "million ", "billion ", "trillion ", "quadrillion ", "quintillion ",
"sextillion ", "septillion ", "octillion ", [0] = ""}
iwords = {"ten ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety
"}
twords = {"eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ",
"eighteen ", "nineteen "}

function digits(n)
  local i, ret = -1
  return function()
    i, ret = i + 1, n % 10
	if n > 0 then
      n = math.floor(n / 10)
	  return i, ret
	end
  end
end

level = false
function getname(pos, dig) --stateful, but effective.
  level = level or pos % 3 == 0
  if(dig == 0) then return "" end
  local name = (pos % 3 == 1 and iwords[dig] or words[dig]) .. (pos % 3 == 2 and "hundred " or "")
  if(level) then name, level = name .. levels[math.floor(pos / 3)], false end
  return name
end

local val, vword = io.read() + 0, ""

for i, v in digits(val) do
  vword = getname(i, v) .. vword
end

for i, v in ipairs(words) do
  vword = vword:gsub("ty " .. v, "ty-" .. v)
  vword = vword:gsub("ten " .. v, twords[i])
end

if #vword == 0 then print "zero" else print(vword) end
singles = " one two three four five six seven eight nine ".split
teens = "ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen ".split
tys = "  twenty thirty forty fifty sixty seventy eighty ninety".split
ions = "thousand million billion".split

numberName = function(n)
    if n == 0 then return "zero"
    a = abs(n)
    r = ""  // (result)
    for u in ions
        h = a % 100
        if h > 0 and h < 10 then r = singles[h] + " " + r
        if h > 9 and h < 20 then r = teens[h-10] + " " + r
        if h > 19 and h < 100 then r = tys[h/10] + "-"*(h%10>0) + singles[h%10] + " " + r
        h = floor((a % 1000) / 100)
        if h then r = singles[h] + " hundred " + r
        a = floor(a / 1000)
        if a == 0 then break
        if a % 1000 > 0 then r = u + " " + r
    end for
    if n < 0 then r = "negative " + r
    return r
end function

// Test cases:
for n in [-1234, 0, 7, 42, 4325, 1000004, 214837564]
    print n + ": " + numberName(n)
end for
Palindrome detection
LuaMiniScript
function ispalindrome(s) return s == string.reverse(s) end
isPalindrome = function(s)
    // convert to lowercase, and strip non-letters
    stripped = ""
    for c in s.lower
    	if c >= "a" and c <= "z" then stripped = stripped + c
    end for

    // check palindromity
    mid = floor(stripped.len/2)
    for i in range(0, mid)
    	if stripped[i] != stripped[-i - 1] then return false
    end for
    return true
end function

testStr = "Madam, I'm Adam"
answer = [testStr, "is"]
if not isPalindrome(testStr) then answer.push "NOT"
answer.push "a palindrome"
print answer.join
Pangram checker
LuaMiniScript
require"lpeg"
S, C = lpeg.S, lpeg.C
function ispangram(s)
  return #(C(S(s)^0):match"abcdefghijklmnopqrstuvwxyz") == 26
end

print(ispangram"waltz, bad nymph, for quick jigs vex")
print(ispangram"bobby")
print(ispangram"long sentence")
sentences = ["The quick brown fox jumps over the lazy dog.",
    "Peter Piper picked a peck of pickled peppers.",
    "Waltz job vexed quick frog nymphs."]

alphabet = "abcdefghijklmnopqrstuvwxyz"

pangram = function (toCheck)
    sentence = toCheck.lower
    fail = false
    for c in alphabet
        if sentence.indexOf(c) == null then return false
    end for
    return true
end function

for sentence in sentences
    if pangram(sentence) then
        print """" + sentence + """ is a Pangram"
    else
        print """" + sentence + """ is not a Pangram"
    end if
end for
Parsing/RPN calculator algorithm
LuaMiniScript
local stack = {}
function push( a ) table.insert( stack, 1, a ) end
function pop()
    if #stack == 0 then return nil end
    return table.remove( stack, 1 )
end
function writeStack()
    for i = #stack, 1, -1 do
        io.write( stack[i], " " )
    end
    print()
end
function operate( a )
    local s
    if a == "+" then
        push( pop() + pop() )
        io.write( a .. "\tadd\t" ); writeStack()
    elseif a == "-" then
        s = pop(); push( pop() - s )
        io.write( a .. "\tsub\t" ); writeStack()
    elseif a == "*" then
        push( pop() * pop() )
        io.write( a .. "\tmul\t" ); writeStack()
    elseif a == "/" then
        s = pop(); push( pop() / s )
        io.write( a .. "\tdiv\t" ); writeStack()
    elseif a == "^" then
        s = pop(); push( pop() ^ s )
        io.write( a .. "\tpow\t" ); writeStack()
    elseif a == "%" then
        s = pop(); push( pop() % s )
        io.write( a .. "\tmod\t" ); writeStack()
    else
        push( tonumber( a ) )
        io.write( a .. "\tpush\t" ); writeStack()
    end
end
function calc( s )
    local t, a = "", ""
    print( "\nINPUT", "OP", "STACK" )
    for i = 1, #s do
        a = s:sub( i, i )
        if a == " " then operate( t ); t = ""
        else t = t .. a 
        end
    end
    if a ~= "" then operate( a ) end
    print( string.format( "\nresult: %.13f", pop() ) )
end
--[[ entry point ]]--
calc( "3 4 2 * 1 5 - 2 3 ^ ^ / +" )
calc( "22 11 *" )
RPN = function(inputText)
    tokens = inputText.split
    stack = []
    while tokens
        tok = tokens.pull
        if "+-*/^".indexOf(tok) != null then
            b = stack.pop
            a = stack.pop
            if tok == "+" then stack.push a + b
            if tok == "-" then stack.push a - b
            if tok == "*" then stack.push a * b
            if tok == "/" then stack.push a / b
            if tok == "^" then stack.push a ^ b
        else
            stack.push val(tok)
        end if
        print tok + " --> " + stack
    end while
    return stack[0]
end function

print RPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")
Penney's game
LuaMiniScript
function penny_game()
    local player, computer = "", ""
    function player_choose()
        io.write( "Enter your sequence of three H and/or T: " )
        local t = io.read():upper()
        if #t > 3 then t = t:sub( 1, 3 )
        elseif #t < 3 then return ""
        end

        for i = 1, 3 do
            c = t:sub( i, i )
            if c ~= "T" and c ~= "H" then
                print( "Just H's and T's!" )
                return ""
            end
        end
        return t
    end
    function computer_choose()
        local t = ""
        if #player > 0 then
            if player:sub( 2, 2 ) == "T" then
                t = "H"
            else
                t = "T";
            end
            t = t .. player:sub( 1, 2 )
        else
            for i = 1, 3 do
                if math.random( 2 ) == 1 then
                    t = t .. "H"
                else
                    t = t .. "T"
                end
            end
        end
        return t
    end
    if math.random( 2 ) == 1 then
        computer = computer_choose()
        io.write( "My sequence is: " .. computer .. "\n" )
        while( true ) do
            player = player_choose()
            if player:len() == 3 then break end
        end
    else
        while( true ) do
            player = player_choose()
            if player:len() == 3 then break end
        end
        computer = computer_choose()
        io.write( "My sequence is: " .. computer .. "\n" )
    end
    local coin, i = "", 1
    while( true ) do
        if math.random( 2 ) == 1 then
            coin = coin .. "T"
            io.write( "T" )
        else
            coin = coin .. "H"
            io.write( "H" )
        end
        if #coin > 2 then
            local seq = coin:sub( i, i + 2 )
            i = i + 1
            if seq == player then
                print( "\nPlayer WINS!!!" )
                return 1
            elseif seq == computer then
                print( "\nComputer WINS!!!" )
                return -1
            end
        end
    end
end
math.randomseed( os.time() )
local cpu, user = 0, 0
repeat
    r = penny_game()
    if r > 0 then
        user = user + 1
    else
        cpu = cpu + 1
    end
    print( "Player: " .. user .. " CPU: " .. cpu )
    io.write( "Play again (Y/N)? " )
    r = io.read()
until( r == "N" or r == "n" )
randomTorH = function()
    if rnd < 0.5 then return "T" else return "H"
end function

if rnd < 0.5 then
    playerSeq = input("Input your sequence (e.g. HTH): ").upper
    if playerSeq[1] == "T" then compSeq = "H" else compSeq = "T"
    compSeq = compSeq + playerSeq[:2]
    print "I choose: " + compSeq
else
    compSeq = randomTorH + randomTorH + randomTorH
    print "I choose: " + compSeq
    playerSeq = input("Input your sequence (e.g. HTH): ").upper
end if

print "Here we go..."
seq = ""
while true
    flip = randomTorH
    print flip
    seq = seq + flip
    if seq[-3:] == playerSeq then
        print "You win!"
        break
    else if seq[-3:] == compSeq then
        print "I win!"
        break
    end if
    wait
end while
Phrase reversals
LuaMiniScript
-- Return a copy of table t in which each string is reversed
function reverseEach (t)
    local rev = {}
    for k, v in pairs(t) do rev[k] = v:reverse() end
    return rev
end

-- Return a reversed copy of table t
function tabReverse (t)
    local revTab = {}
    for i, v in ipairs(t) do revTab[#t - i + 1] = v end
    return revTab
end

-- Split string str into a table on space characters
function wordSplit (str)
    local t = {}
    for word in str:gmatch("%S+") do table.insert(t, word) end
    return t
end

-- Main procedure
local str = "rosetta code phrase reversal"
local tab = wordSplit(str)
print("1. " .. str:reverse())
print("2. " .. table.concat(reverseEach(tab), " "))
print("3. " .. table.concat(tabReverse(tab), " "))
phrase = "rosetta code phrase reversal"

// general sequence reversal function
reverse = function(seq)
    out = []
    for i in range(seq.len-1, 0)
        out.push seq[i]
    end for
    if seq isa string then return out.join("")
    return out
end function

// 1. Reverse the characters of the string.
print reverse(phrase)

// 2. Reverse the characters of each individual word in the string, maintaining original word order
within the string.
words = phrase.split
for i in words.indexes
    words[i] = reverse(words[i])
end for
print words.join

// 3. Reverse the order of each word of the string, maintaining the order of characters in each
word.
print reverse(phrase.split).join
Pig the dice game
LuaMiniScript
local numPlayers = 2
local maxScore = 100
local scores = { }
for i = 1, numPlayers do
	scores[i] = 0  -- total safe score for each player
end
math.randomseed(os.time())
print("Enter a letter: [h]old or [r]oll?")
local points = 0 -- points accumulated in current turn
local p = 1 -- start with first player
while true do
	io.write("\nPlayer "..p..", your score is ".. scores[p]..", with ".. points.." temporary points. 
")
	local reply = string.sub(string.lower(io.read("*line")), 1, 1)
	if reply == 'r' then
		local roll = math.random(6)
		io.write("You rolled a " .. roll)
		if roll == 1 then
			print(".  Too bad. :(")
			p = (p % numPlayers) + 1
			points = 0
		else
			points = points + roll
		end
	elseif reply == 'h' then
		scores[p] = scores[p] + points
		if scores[p] >= maxScore then
			print("Player "..p..", you win with a score of "..scores[p])
			break
		end
		print("Player "..p..", your new score is " .. scores[p])
		p = (p % numPlayers) + 1
		points = 0
	end
end
// Pig the Dice for two players.
Player = {}
Player.score = 0
Player.doTurn = function()
    rolls = 0
    pot = 0
    print self.name + "'s Turn!"
    while true
        if self.score + pot >= goal then
            print "   " + self.name.upper + " WINS WITH " + (self.score + pot) + "!"
            inp = "H"
        else
            inp = input(self.name + ", you have " + pot + " in the pot.  [R]oll or Hold? ")
        end if
        if inp == "" or inp[0].upper == "R" then
            die = ceil(rnd*6)
            if die == 1 then
                print "   You roll a 1.  Busted!"
                return
            else
                print "   You roll a " + die + "."
                pot = pot + die
            end if
        else
            self.score = self.score + pot
            return
        end if
    end while
end function

p1 = new Player
p1.name = "Alice"
p2 = new Player
p2.name = "Bob"
goal = 100

while p1.score < goal and p2.score < goal
    for player in [p1, p2]
        print
        print p1.name + ": " + p1.score + "  |  " + p2.name + ": " + p2.score
        player.doTurn
        if player.score >= goal then break
    end for
end while
Playing cards
LuaMiniScript
suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
--a stack is a set of cards. a stack of length 1 acts as a card; the stack constructor only creates
decks.

stack = setmetatable({
--shuffles a stack
__unm = function(z)
  local ret = {}
  for i = #z, 1, -1 do
    ret[#ret + 1] = table.remove(z,math.random(i))
  end
  return setmetatable(ret, stack)
end,
--puts two stacks together
__add = function(z, z2)
  for i = 1, #z2 do
    z[#z+1] = table.remove(z2)
  end
  return z
end,
--removes n cards from a stack and returns a stack of those cards
__sub = function(z, n)
  local ret = {}
  for i = 1, n do
    ret[i] = table.remove(z)
  end
  return setmetatable(ret, stack)
end,
--breaks a stack into n equally sized stacks and returns them all
deal = function(z, n)
  local ret = {}
  for i = 1, #z/n do
    ret[i] = table.remove(z)
  end
  if n > 1 then return setmetatable(ret, stack), stack.deal(z,n-1)
  else return setmetatable(ret, stack)
  end
end,
--returns a and b as strings, concatenated together. Simple enough, right?
__concat = function(a, b)
  if getmetatable(a) == stack then
    return stack.stackstring(a) .. b
  else
    return a .. stack.stackstring(b)
  end
end,
stackstring = function(st, ind)
    ind = ind or 1
	if not st[ind] then return "" end
	return st[ind] and (faces[math.ceil(st[ind]/4)] .. " of " .. suits[st[ind]%4+1] .. "\n" ..
stack.stackstring(st, ind+1)) or ""
end}, {
--creates a deck
__call = function(z)
  local ret = {}
  for i = 1, 52 do ret[i] = i end
  return -setmetatable(ret,z)
end})

print(stack() .. "\n")
a, b, c, d = stack.deal(stack(), 4)
print(a .. "\n\n\n")
print(b + c .. "\n\n\n")
print(d - 4 .. "")
print(-b .. "")
suits = ["Spades", "Clubs", "Hearts", "Diamonds"]
pips = ["Ace","Two","Three","Four","Five","Six","Seven",
    "Eight","Nine","Ten","Jack","Queen","King"]

Card = {}
Card.str = function()
    return self.pip + " of " + self.suit + " (value: " + self.value + ")"
end function

//Build Deck
deck = []
for s in suits.indexes
    for p in pips.indexes
        card = new Card
        card.suit = suits[s]
        card.pip = pips[p]
        card.value = s * 100 + p
        deck.push card
    end for
end for
 
draw = function(count=7)
    hand = []
    for i in range(1, count)
        hand.push deck.pop
    end for
    return hand
end function
 
display = function(stack)
    for card in stack
        print card.str
    end for
end function
 
print "Deck created. Cards in Deck: " + deck.len
 
deck.shuffle
print "Deck Shuffled"
 
hand = draw
print "First hand: "
display hand

print
print deck.len + " cards left in deck:"
display deck
Polymorphic copy
LuaMiniScript
T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }

function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end
S1 = clone(T)  S1.name=function(s) return "S1" end

function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end
S2 = merge(clone(T), {name=function(s) return "S2" end})

function prototype(base,mixin) return merge(merge(clone(base),mixin),{prototype=base}) end
S3 = prototype(T, {name=function(s) return "S3" end})

print("T :  "..T:tostring())
print("S1:  " ..S1:tostring())
print("S2:  " ..S2:tostring())
print("S3:  " ..S3:tostring())
print("S3's parent:  "..S3.prototype:tostring())
T = {}
T.foo = function()
    return "This is an instance of T"
end function

S = new T
S.foo = function()
    return "This is an S for sure"
end function

instance = new S
print "instance.foo: " + instance.foo

copy = {}
copy = copy + instance  // copies all elements
print "copy.foo: " + copy.foo

// And to prove this is a copy, and not a reference:
instance.bar = 1
copy.bar = 2
print "instance.bar: " + instance.bar
print "copy.bar: " + copy.bar
Quine
LuaMiniScript
s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s)
s="s=;print s[:2]+char(34)+s+char(34)+s[2:]";print s[:2]+char(34)+s+char(34)+s[2:]
Random numbers
LuaMiniScript
local list = {}
for i = 1, 1000 do
  list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
end
randNormal = function(mean=0, stddev=1)
    return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function

x = []
for i in range(1,1000)
    x.push randNormal(1, 0.5)
end for
Range expansion
LuaMiniScript
function range(i, j)
    local t = {}
    for n = i, j, i<j and 1 or -1 do
        t[#t+1] = n
    end
    return t
end

function expand_ranges(rspec)
    local ptn = "([-+]?%d+)%s?-%s?([-+]?%d+)"
    local t = {}

    for v in string.gmatch(rspec, '[^,]+') do
        local s, e = v:match(ptn)

        if s == nil then
            t[#t+1] = tonumber(v)
        else
            for i, n in ipairs(range(tonumber(s), tonumber(e))) do
                t[#t+1] = n
            end
        end
    end
    return t
end

local ranges = "-6,-3--1,3-5,7-11,14,15,17-20"
print(table.concat(expand_ranges(ranges), ', '))
pullInt = function(chars)
    numstr = chars.pull
    while chars and chars[0] != "," and chars[0] != "-"
        numstr = numstr + chars.pull
    end while
    return val(numstr)
end function
    
expandRange = function(s)
    result = []
    chars = s.split("")
    while chars
        num = pullInt(chars)
        if not chars or chars.pull == "," then
            result.push num
        else
            result = result + range(num, pullInt(chars))
            chars.pull  // skip "," after range
        end if
    end while
    return result
end function

print expandRange("-6,-3--1,3-5,7-11,14,15,17-20")
Range extraction
LuaMiniScript
function extractRange (rList)
    local rExpr, startVal = ""
    for k, v in pairs(rList) do
        if rList[k + 1] == v + 1 then
            if not startVal then startVal = v end
        else
            if startVal then
                if v == startVal + 1 then
                    rExpr = rExpr .. startVal .. "," .. v .. ","
                else
                    rExpr = rExpr .. startVal .. "-" .. v .. ","
                end
                startVal = nil
            else
                rExpr = rExpr .. v .. ","
            end
        end
    end
    return rExpr:sub(1, -2)
end

local intList = {
    0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
   15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
   25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
   37, 38, 39
}
print(extractRange(intList))
extractRange = function(ints)
    result = []
    idx = 0
    while idx < ints.len
        runLen = 1
        while idx+runLen < ints.len and ints[idx+runLen] == ints[idx] + runLen
            runLen = runLen + 1
        end while
        if runLen > 2 then
            result.push ints[idx] + "-" + ints[idx+runLen-1]
            idx = idx + runLen
        else
            result.push ints[idx]
            idx = idx + 1
        end if
    end while
    return join(result, ",")
end function

test = [ 0,  1,  2,  4,  6,  7,  8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
   25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]
print extractRange(test)
Remove duplicate elements
LuaMiniScript
items = {1,2,3,4,1,2,3,4,"bird","cat","dog","dog","bird"}
flags = {}
io.write('Unique items are:')
for i=1,#items do
   if not flags[items[i]] then
      io.write(' ' .. items[i])
      flags[items[i]] = true
   end
end
io.write('\n')
items = [1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"]
d = {}
for i in items
    d.push i
end for
print d.indexes
Repeat
LuaMiniScript
function myFunc ()
    print("Sure looks like a function in here...")
end

function rep (func, times)
    for count = 1, times do
        func()
    end
end

rep(myFunc, 4)
sayHi = function()
    print "Hi!"
end function

rep = function(f, n)
    for i in range(1, n)
        f
    end for
end function

rep @sayHi, 3
Repeat a string
LuaMiniScript
function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end
str = "Lol"
print str * 5
Reverse a string
LuaMiniScript
theString = theString:reverse()
str = "This is a string"
print "Forward: " + str
newStr = ""
for i in range(str.len-1, 0)
    newStr = newStr + str[i]
end for
print "Reversed: " + newStr
Reverse the gender of a string
LuaMiniScript
function sufficient(s)
  local xref = { She="He", He="She" }
  return (s:gsub("(%w+)", function(s) return xref[s] or s end))
end
s = "She was a soul stripper. She took my heart!"
print(sufficient(s))
print(sufficient(sufficient(s)))
print(sufficient(sufficient(s)) == s)
cap = function(w)   // (capitalize a word)
    return w[0].upper + w[1:]
end function

trans = {"she":"he", "her":"his", "hers":"his"}
trans = trans + {"he":"she", "his":"her", "him":"her"}

for k in trans.indexes
    trans[cap(k)] = cap(trans[k])
end for

reverseGender = function(s)
    s = s.replace(".", " .").replace(",", " ,").replace("?", " ?").replace("!", " !")
    words = s.split
    for i in words.indexes
        if trans.hasIndex(words[i]) then words[i] = trans[words[i]]
    end for
    s = words.join
    s = s.replace(" .", ".").replace(" ,", ",").replace(" ?", "?").replace(" !", "!")
    return s
end function

test = function(s)
    print "BEFORE: " + s
    print "AFTER:  " + reverseGender(s)
    print
end function

test "She was a soul stripper. She took his heart!"
test "He was a soul stripper. He took her heart!"
test "She wants what's hers, he wants her and she wants him!"
test "Her dog belongs to him but his dog is hers!"
Reverse words in a string
LuaMiniScript
local lines = {}
for line in (s .. "\n"):gmatch("(.-)\n") do
	local this = {}
	for word in line:gmatch("%S+") do
		table.insert(this, 1, word)
	end
	lines[#lines + 1] = table.concat(this, " ")
end
print(table.concat(lines, "\n"))
lines = ["==========================================",
    "|  ---------- Ice and Fire ------------  |",
    "|                                        |",
    "|  fire, in end will world the say Some  |",
    "|  ice. in say Some                      |",
    "|  desire of tasted I've what From       |",
    "|  fire. favor who those with hold I     |",
    "|                                        |",
    "|  ... elided paragraph last ...         |",
    "|                                        |",
    "|  Frost Robert -----------------------  |",
    "=========================================="]
    
for line in lines
    oldLine = line.split
    newLine = []
    while oldLine
// the line below line retains the outer box format
        newLine.push oldLine.pop
// alternate format, replace above line with below two lines below to strip all superfluous spaces
//	word = oldLine.pop
//	if word != "" then newLine.push word
    end while
    print newLine.join
end for
Roots of unity
LuaMiniScript
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a
conversion to strgs.
complex = setmetatable({
__add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end,
__sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end,
__mul = function(u, v) return complex(u.real * v.real - u.imag * v.imag, u.real * v.imag + u.imag *
v.real) end,
__div = function(u, v) return u * complex(v.real / v.norm, -v.imag / v.norm) end,
__unm = function(u) return complex(-u.real, -u.imag) end,
__concat = function(u, v)
    if type(u) == "table" then return u.real .. " + " .. u.imag .. "i" .. v
	elseif type(u) == "string" or type(u) == "number" then return u .. v.real .. " + " .. v.imag .. "i"
	end end,
__index = function(u, index)
  local operations = {
    norm = function(u) return u.real ^ 2 + u.imag ^ 2 end,
    conj = function(u) return complex(u.real, -u.imag) end,
  }
  return operations[index] and operations[index](u)
end,
__newindex = function() error() end
}, {
__call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart},
complex) end
} )
n = io.read() + 0
val = complex(math.cos(2*math.pi / n), math.sin(2*math.pi / n))
root = complex(1, 0)
for i = 1, n do
  root = root * val
  print(root .. "")
end
complexRoots = function(n)
    result = []
    for i in range(0, n-1)
        real = cos(2*pi * i/n)
        if abs(real) < 1e-6 then real = 0
        imag = sin(2*pi * i/n)
        if abs(imag) < 1e-6 then imag = 0
        result.push real + " " + "+" * (imag>=0) + imag + "i"
    end for
    return result
end function

for i in range(2,5)
    print i + ": " + complexRoots(i).join(", ")
end for
Rot-13
LuaMiniScript
function rot13(s)
	local a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
	return (s:gsub("%a", function(c) return b:sub(a:find(c)) end))
end
rot13 = function(s)
    chars = s.values
    for i in chars.indexes
        c = chars[i]
        if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+13)%26)
        if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+13)%26)
    end for
    return chars.join("")
end function

print rot13("Hello world!")
print rot13("Uryyb jbeyq!")
Self-describing numbers
LuaMiniScript
function Is_self_describing( n )
    local s = tostring( n )

    local t = {}
    for i = 0, 9 do t[i] = 0 end

    for i = 1, s:len() do
	local idx = tonumber( s:sub(i,i) )
        t[idx] = t[idx] + 1
    end

    for i = 1, s:len() do
        if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end
    end

    return true
end

for i = 1, 999999999 do
    print( Is_self_describing( i ) )
end
numbers = [12, 1210, 1300, 2020, 21200, 5]
 
occurrences = function(test, values)
    count = 0
    for i in values
        if i.val == test then count = count + 1
    end for
    return count
end function
 
for number in numbers
    check = "" + number
    digits = check.values
    describing = true
    for digit in digits.indexes
        if digits[digit].val != occurrences(digit, digits) then
            describing = false
        end if
    end for
    if describing then
        print number + " is self describing"
    else
        print number + " is not self describing"
    end if
end for
Semiprime
LuaMiniScript
function semiprime (n)
	local divisor, count = 2, 0
	while count < 3 and n ~= 1 do
		if n % divisor == 0 then
			n = n / divisor
			count = count + 1
		else
			divisor = divisor + 1
		end
	end
	return count == 2
end

for n = 1675, 1680 do
	print(n, semiprime(n))
end
isSemiprime = function(num)
    divisor = 2
    primes = 0
    while primes < 3 and num != 1
        if num % divisor == 0 then
            num = num / divisor;
            primes = primes + 1
        else
            divisor = divisor + 1
        end if
    end while
    return primes == 2
end function

print "Semiprimes up to 100:"
results = []
for i in range(2, 100)
    if isSemiprime(i) then results.push i
end for
print results
Shoelace formula for polygonal area
LuaMiniScript
function shoeArea(ps)
  local function det2(i,j)
    return ps[i][1]*ps[j][2]-ps[j][1]*ps[i][2]
  end
  local sum = #ps>2 and det2(#ps,1) or 0
  for i=1,#ps-1 do sum = sum + det2(i,i+1)end
  return math.abs(0.5 * sum)
end
shoelace = function(vertices)
    sum = 0
    points = vertices.len
    
    for i in range(0,points-2)
        sum = sum + vertices[i][0]*vertices[i+1][1]
    end for
    sum = sum + vertices[points-1][0]*vertices[0][1]
    
    for i in range(points-1,1)
        sum = sum - vertices[i][0]*vertices[i-1][1]
    end for
    sum = sum - vertices[0][0]*vertices[points-1][1]
    
    return abs(sum)/2
end function

verts = [[3,4],[5,11],[12,8],[9,5],[5,6]]

print "The polygon area is "  + shoelace(verts)
Show ASCII table
LuaMiniScript
-- map of character values to desired representation
local chars = setmetatable({[32] = "Spc", [127] = "Del"}, {__index = function(_, k) return
string.char(k) end})

-- row iterator
local function iter(s,a) 
  a = (a or s) + 16
  if a <= 127 then return a, chars[a] end 
end

-- print loop
for i = 0, 15 do 
   for j, repr in iter, i+16 do 
      io.write(("%3d : %3s    "):format(j, repr))
   end
   io.write"\n"
end
// Prints ASCII table
// Note changing the values of startChar and endChar will print
// a flexible table in that range
 
startChar = 32
endChar = 127
characters = []
 
for i in range(startChar, endChar)
    addString = char(i) + "  "
    if i == 32 then addString = "SPC"
    if i == 127 then addString = "DEL"
    characters.push addString
end for
 
for i in characters.indexes
    iNum = i + startChar
    iChar = "     " + str(iNum)
    characters[i] = iChar[-5:] + " : " + characters[i]
end for
 
columns = 6
line = ""
col = 0
for out in characters
    col = col + 1
    line = line + out
    if col == columns then
        print line
        line = ""
        col = 0
    end if
end for
if line then print line // final check for odd incomplete line output
Spinning rod animation/Text
LuaMiniScript
--
-- Simple String Animation - semi-hard-coded variant - you can alter the chars table - update the
count and run it...
--

-- The basic animation runtime controller. This is where you assign the active animation ( you could
create a simple function to replace the animation table and nil count, index and expiry to extend
this system to allow multiple animations -
--	and since you can replace after a previous has been output, it would appear as though you were
running different animations at the same time - that wouldn't be async compatible though )...
-- So you can either activate the animation you want permanently, or create a simple function to
update the animation table and reset the control variables... ie: ( function
string.SetBasicAnimation( _tab_of_chars ) string.__basic_anim_runtime.anim = _tab_of_chars;
string.__basic_anim_runtime.index = nil; string.__basic_anim_runtime.count = nil;
string.__basic_anim_runtime.expiry = nil; end )
string.__basic_anim_runtime = {
	-- The animation - can not ping pong... requires full sequence. Resets to first after full
sequence. Dots animation.. Requires center segment because of ping / pong
	anim = { '.', '..', '...', '..' };

	-- Pipes animation - This performs a complete rotation, no need to add extra segments.
	-- anim = { '|', '/', '─', '\\' };

	-- Stars - This is reversible so requires the center segments..
	-- anim = { '⁎', '⁑', '⁂', '⁑' };

	-- Clock - This still needs to be ordered...
	-- anim = { '🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖',
'🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦' };

	-- Arrows - This does a complete circle and doesn't need to reverse
	-- anim = { '⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉' };

	-- Bird Flying - this is reversible so it requires all.. 1 2 3 4 5 6 5 4 3 2
	-- anim = { '︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵' };

	-- Plants - Set as reversible, requires all..
	-- anim = { '☘', '❀', '❁', '❀' };

	-- Eclipse - From Raku Throbber post author
	-- anim = { '🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘' };
};


--
-- The basic animator function - accepts a numerical delay and a boolean backwards switch.. It only
accepts a single animation from the helper local table above..
--
-- Argument - _delay - <Number> - Accepts a time, in seconds with fraction support, that
designates how long a frame should last. Optional. If no number given, it uses the default value of
1 / 8 seconds.
-- Argument - _play_backwards - <Boolean> - Toggles whether or not the animation plays backwards
or forwards. Default is forwards. Optional.
--
-- RETURN: <String> - Character( s ) of the current animation frame - if the frame is invalid, it
returns an empty string.
-- RETURN: <Boolean> - Has Advanced Frame Controller - set to true if this call resulted in a new
frame / index being assigned with new character( s )
--
function string.BasicAnimation( _delay, _play_backwards )
	-- Setup delay - make sure it is a number and Reference our runtime var
	local _delay = ( ( type( _delay ) == 'number' ) and _delay or 1 / 8 ), string.__basic_anim_runtime,
os.clock( );

	-- cache our count so we count once per refresh.
	_data.count = ( type( _data.count ) == 'number' ) and _data.count or #_data.anim;

	-- Setup our helpers...
	local _expiry, _index, _chars, _count, _has_advanced_frame = _data.expiry, ( _data.index or (
_play_backwards and _data.count or 1 ) ), _data.anim, _data.count, false;

	-- If expiry has occurred, advance... Expiry can be nil the first call, this is ok because it will
just use the first character - or the last if playing backwards.
	if ( _expiry and _expiry < _time ) then
		-- Advance..
		_index, _has_advanced_frame = ( ( _index + ( 1 * ( _play_backwards and -1 or 1 ) ) ) % ( _count +
1 ) ), true;

		-- If 0, add 1 otherwise keep the same.
		_index = _index < 1 and ( _play_backwards and _count or 1 ) or _index;

		-- Update the index
		_data.index = _index;
	end

	-- Update the trackers and output the char. -- Note: This is best done in the loop, but since we
are checking the expiry above I decided to integrate it here.
	_data.expiry = ( not _data.expiry or _has_advanced_frame ) and _time + _delay or _data.expiry;

	-- Return the character at the index or nothing.
	return _chars[ _index ] or '', _has_advanced_frame;
end


--
-- Helper / OPTIONAL FUNCTION - Updates the animation and resets the controlling variables
--
-- Argument: _tab - <Table> - This is the table containing the animation characters... ie: { '.',
'..', '...', '..' } would be a valid entry. Requires at least 2 entries.
--
function string.SetBasicAnimation( _tab )
	-- Prevent non tables, empty tables, or tables with only 1 entry.
	if not ( type( _tab ) == 'table' and #_tab > 1 ) then return error( 'Can not update basic animation
without argument #1 as a table, with at least 2 entries...' ); end

	-- Helper
	local _data = string.__basic_anim_runtime;

	-- Update the animation table and Clear the controllers...
	_data.anim, _data.count, _data.index, _data.expiry = _tab, nil, nil, nil;
end
print "Press control-C to exit..."
while true
    for c in "|/-\"
        text.setCell 0, 0, c
        wait 0.25
    end for
end while
Split a character string based on change of character
LuaMiniScript
function charSplit (inStr)
    local outStr, nextChar = inStr:sub(1, 1)
    for pos = 2, #inStr do
        nextChar = inStr:sub(pos, pos)
        if nextChar ~= outStr:sub(#outStr, #outStr) then
            outStr = outStr .. ", "
        end
        outStr = outStr .. nextChar
    end
    return outStr
end

print(charSplit("gHHH5YY++///\\"))
s = "gHHH5YY++///\"
output = []
lastLetter = s[0]
for letter in s
    if letter != lastLetter then output.push ", "
    output.push letter
    lastLetter = letter
end for
print output.join("")
Square but not cube
LuaMiniScript
function nthroot (x, n)
  local r = 1
  for i = 1, 16 do
    r = (((n - 1) * r) + x / (r ^ (n - 1))) / n
  end
  return r
end

local i, count, sq, cbrt = 0, 0
while count < 30 do
  i = i + 1
  sq = i * i
  -- The next line should say nthroot(sq, 3), right? But this works. Maths, eh?
  cbrt = nthroot(i, 3)
  if cbrt == math.floor(cbrt) then
    print(sq .. " is square and cube")
  else
    print(sq)
    count = count + 1
  end
end
squares = []
tris = []
both = []
for i in range(1, 100)
    tris.push i*i*i
    if tris.indexOf(i*i) == null then
        squares.push i*i
    else
        both.push i*i
    end if
end for

print "Square but not cube:"
print squares[:30]
print "Both square and cube:"
print both[:3]
Stack
LuaMiniScript
stack = {}
table.insert(stack,3)
print(table.remove(stack)) --> 3
// Note in Miniscript, a value of zero is false,
// and any other number is true.
// therefore the .len function works as the inverse of a .empty function
stack = [2, 4, 6]
stack.push 8
print "Stack is " + stack
print "Adding '9' to stack " + stack.push(9)
print "Top of stack is " + stack.pop
print "Stack is " + stack
if stack.len then
    print "Stack is not empty"
else
    print "Stack is empty"
end if
Statistics/Basic
LuaMiniScript
math.randomseed(os.time())

function randList (n)  -- Build table of size n
	local numbers = {}
	for i = 1, n do
		table.insert(numbers, math.random()) -- range correct by default
	end
	return numbers
end

function mean (t)  -- Find mean average of values in table t
	local sum = 0
	for k, v in pairs(t) do
		sum = sum + v
	end
	return sum / #t
end

function stdDev (t)  -- Find population standard deviation of table t
	local squares, avg = 0, mean(t)
	for k, v in pairs(t) do
		squares = squares + ((avg - v) ^ 2)
	end
	local variance = squares / #t
	return math.sqrt(variance)
end

function showHistogram (t)  -- Draw histogram of given table to stdout
	local histBars, compVal = {}
	for range = 0, 9 do
		histBars[range] = 0
		for k, v in pairs(t) do
			compVal = tonumber(string.format("%0.1f", v - 0.05))
			if compVal == range / 10 then
				histBars[range] = histBars[range] + 1
			end
		end
	end
	for k, v in pairs(histBars) do
		io.write("0." .. k .. " " .. string.rep('=', v / #t * 200))
		print(" " .. v)
	end
	print()
end

function showStats (tabSize)  -- Create and display statistics info
	local numList = randList(tabSize)
	print("Table of size " .. #numList)
	print("Mean average: " .. mean(numList))
	print("Standard dev: " .. stdDev(numList))
	showHistogram(numList)
end

for power = 2, 5 do  -- Start of main procedure
	showStats(10 ^ power)
end
Stats = {}
Stats.count = 0
Stats.sum = 0
Stats.sumOfSquares = 0
Stats.histo = null

Stats.add = function(x)
    self.count = self.count + 1
    self.sum = self.sum + x
    self.sumOfSquares = self.sumOfSquares + x*x
    bin = floor(x*10)
    if not self.histo then self.histo = [0]*10
    self.histo[bin] = self.histo[bin] + 1
end function

Stats.mean = function()
    return self.sum / self.count
end function

Stats.stddev = function()
    m = self.sum / self.count
    return sqrt(self.sumOfSquares / self.count - m*m)
end function

Stats.histogram = function()
    for i in self.histo.indexes
        print "0." + i + ": " + "=" * (self.histo[i]/self.count * 200)
    end for
end function

for sampleSize in [100, 1000, 10000]
    print "Samples: " + sampleSize
    st = new Stats
    for i in range(sampleSize)
        st.add rnd
    end for
    print "Mean: " + st.mean + "  Standard Deviation: " + st.stddev
    st.histogram
end for
String case
LuaMiniScript
str = "alphaBETA"
print( string.upper(str) )
print( string.lower(str) )
mixedString = "alphaBETA"
print "Upper Case of " + mixedString + " is " + mixedString.upper
print "Lower Case of " + mixedString + " is " + mixedString.lower
String comparison
LuaMiniScript
function compare(a, b)
    print(("%s is of type %s and %s is of type %s"):format(
        a, type(a),
        b, type(b)
    ))
    if a <  b then print(('%s is strictly less than %s'):format(a, b)) end
    if a <= b then print(('%s is less than or equal to %s'):format(a, b)) end
    if a >  b then print(('%s is strictly greater than %s'):format(a, b)) end
    if a >= b then print(('%s is greater than or equal to %s'):format(a, b)) end
    if a == b then print(('%s is equal to %s'):format(a, b)) end
    if a ~= b then print(('%s is not equal to %s'):format(a, b)) end
    print ""
end
 
compare('YUP', 'YUP')
compare('BALL', 'BELL')
compare('24', '123')
compare(24, 123)
compare(5.0, 5)
string1 = input("Please enter a string.")
string2 = input("Please enter a second string.")

//Comparing two strings for exact equality

if string1 == string2 then
    print "Strings are equal."
end if

//Comparing two strings for inequality

if string1 != string2 then
    print "Strings are NOT equal."
end if

//Comparing two strings to see if one is lexically ordered before than the other

if string1 > string2 then
    print string1 + " is lexically ordered AFTER " + string2
    
//Comparing two strings to see if one is lexically ordered after than the other

else if string1 < string2 then
    print string1 + " is lexically ordered BEFORE " + string2
end if

//How to achieve case sensitive comparisons

//Comparing two strings for exact equality (case sensitive)
if string1 == string2 then
    print "Strings are equal. (case sensitive)"
end if

//Comparing two strings for inequality (case sensitive)
if string1 != string2 then
    print "Strings are NOT equal. (case sensitive)"
end if

//How to achieve case insensitive comparisons within the language

//Comparing two strings for exact equality (case insensitive)
if string1.lower == string2.lower then
    print "Strings are equal. (case insensitive)"
end if

//Comparing two strings for inequality (case insensitive)
if string1.lower != string2.lower then
    print "Strings are NOT equal. (case insensitive)"
end if
String concatenation
LuaMiniScript
a = "hello "
print(a .. "world")
c = a .. "world"
print(c)
s = "hello"
print s + " world!"
String matching
LuaMiniScript
s1 = "string"
s2 = "str"
s3 = "ing"
s4 = "xyz"

print( "s1 starts with s2: ", string.find( s1, s2 ) == 1 )
print( "s1 starts with s3: ", string.find( s1, s3 ) == 1, "\n" )

print( "s1 contains s3: ", string.find( s1, s3 ) ~= nil )
print( "s1 contains s3: ", string.find( s1, s4 ) ~= nil, "\n" )   
   
print( "s1 ends with s2: ", select( 2, string.find( s1, s2 ) ) == string.len( s1 ) )
print( "s1 ends with s3: ", select( 2, string.find( s1, s3 ) ) == string.len( s1 ) )
string.startsWith = function(s)
    return self.len >= s.len and s[:s.len] == s
end function

string.endsWith = function(s)
    return self.len >= s.len and s[-s.len:] == s
end function

string.findAll = function(s)
    result = []
    after = null
    while true
        foundPos = self.indexOf(s, after)
        if foundPos == null then return result
        result.push foundPos
        after = foundPos + s.len - 1
    end while
end function
    
first = "The brown dog jumped jumped and jumped"
second = "jumped"

firstQ = """" + first + """"  // (first string, in quotes)
secondQ = """" + second + """"
doesOrNot = [" does not ", " does "]

print firstQ + doesOrNot[first.startsWith(second)] + "start with " + secondQ
print

found = first.findAll(second)
if not found then
    print firstQ + " does not contain " + secondQ + " anywhere"
else
    for pos in found
        print firstQ + " is found at position " + pos + " in " + secondQ
    end for
end if
print

print firstQ + doesOrNot[first.endsWith(second)] + "end with " + secondQ
Strip comments from a string
LuaMiniScript
comment_symbols = ";#"

s1 = "apples, pears # and bananas"
s2 = "apples, pears ; and bananas"

print ( string.match( s1, "[^"..comment_symbols.."]+" ) )
print ( string.match( s2, "[^"..comment_symbols.."]+" ) )
strip = function(test)
    comment = test.indexOf("#")
    if comment == null then comment = test.indexOf(";")
    if comment then test = test[:comment]
    while test[-1] == " "
        test = test - " "
    end while
    return test
end function

print strip("This is a hash test    # a comment") + "."
print strip("This is a semicolon test   ;  a comment") + "."
print strip("This is a no comment test   ") + "."
Subleq
LuaMiniScript
function subleq (prog)
    local mem, p, A, B, C = {}, 0
    for word in prog:gmatch("%S+") do
        mem[p] = tonumber(word)
        p = p + 1
    end
    p = 0
    repeat
        A, B, C = mem[p], mem[p + 1], mem[p + 2]
        if A == -1 then
            mem[B] = io.read()
        elseif B == -1 then
            io.write(string.char(mem[A]))
        else
            mem[B] = mem[B] - mem[A]
            if mem[B] <= 0 then p = C end
        end
        p = p + 3
    until not mem[mem[p]]
end

subleq("15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100
33 10 0")
memory = []
step = 3
currentAddress = 0
out = ""

process = function(address)
    A = memory[address].val
    B = memory[address + 1].val
    C = memory[address + 2].val
    nextAddress = address + step
    
    if A == -1 then
        memory[B] = input
    else if B == -1 then
        globals.out = globals.out + char(memory[A].val)
    else
        memory[B] = str(memory[B].val - memory[A].val)
        if memory[B] < 1 then nextAddress = C
    end if
    return nextAddress
end function

print
memory = input("Enter SUBLEQ program").split

print
print "Running Program"
print "-------------------"
processing = currentAddress < memory.len
while processing
    currentAddress = process(currentAddress)
    if currentAddress >= memory.len or currentAddress == -1 then
        processing = false
    end if
end while

print out
print "-------------------"
print "Execution Complete"
Substitution cipher
LuaMiniScript
-- Generate a random substitution cipher for ASCII characters 65 to 122
function randomCipher ()
    local cipher, rnd = {plain = {}, encoded = {}}
    for ascii = 65, 122 do
        table.insert(cipher.plain, string.char(ascii))
        table.insert(cipher.encoded, string.char(ascii))
    end
    for i = 1, #cipher.encoded do
        rnd = math.random(#cipher.encoded)
        cipher.encoded[i], cipher.encoded[rnd] = cipher.encoded[rnd], cipher.encoded[i]
    end
    return cipher
end

-- Encipher text using cipher.  Decipher if decode is true.
function encode (text, cipher, decode)
    local output, letter, found, source, dest = ""
    if decode then
        source, dest = cipher.encoded, cipher.plain
    else
        source, dest = cipher.plain, cipher.encoded
    end
    for pos = 1, #text do
        letter = text:sub(pos, pos)
        found = false
        for k, v in pairs(source) do
            if letter == v then
                output = output .. dest[k]
                found = true
                break
            end
        end
        if not found then output = output .. letter end
    end
    return output
end

-- Main procedure
math.randomseed(os.time())
local subCipher = randomCipher()
print("Cipher generated:")
print("\tPlain:", table.concat(subCipher.plain))
print("\tCoded:", table.concat(subCipher.encoded))
local inFile = io.open("C:\\ulua\\taskDescription.txt", "r")
local input = inFile:read("*all")
inFile:close()
local encoded = encode(input, subCipher)
print("\nEncoded file contents:")
print("\t" .. encoded)
print("\nAbove text deciphers to: ")
print("\t" .. encode(encoded, subCipher, true))
alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
encode = {}
decode = {}
for i in alphabet.indexes
    encode[alphabet[i]] = cipher[i]
    decode[cipher[i]] = alphabet[i]
    encode[alphabet[i].upper] = cipher[i].upper
    decode[cipher[i].upper] = alphabet[i].upper
end for

apply = function(map, s)
    chars = s.split("")
    for i in chars.indexes
        if map.hasIndex(chars[i]) then chars[i] = map[chars[i]]
    end for
    return chars.join("")
end function

msg = "Now is the time for all good men (and women) to come together."
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)
Substring/Top and tail
LuaMiniScript
print (string.sub("knights",2))    -- remove the first character
print (string.sub("knights",1,-2))    -- remove the last character
print (string.sub("knights",2,-2))    -- remove the first and last characters
test = "This thing"
print test[1:]
print test[:-1]
print test[1:-1]
Sum multiples of 3 and 5
LuaMiniScript
function tri (n) return n * (n + 1) / 2 end

function sum35 (n)
	n = n - 1
	return	(	3 * tri(math.floor(n / 3)) + 
			5 * tri(math.floor(n / 5)) - 
			15 * tri(math.floor(n / 15))
		)
end

print(sum35(1000))
print(sum35(1e+20))
// simple version:
sum35 = function(n)
    sum = 0
    for i in range(3, n-1, 3)
        sum = sum + i
    end for
    for i in range(5, n-1, 5)
        if i % 3 then sum = sum + i // (skip multiples of 3 here)
    end for
    return sum
end function

print sum35(1000)
Sum of a series
LuaMiniScript
sum = 0
for i = 1, 1000 do sum = sum + 1/i^2 end
print(sum)
zeta = function(num)
    return 1 / num^2
end function

sum = function(start, finish, formula)
    total = 0
    for i in range(start, finish)
        total = total + formula(i)
    end for
    return total
end function

print sum(1, 1000, @zeta)
Sum of squares
LuaMiniScript
function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end
function squaresumt(t) return squaresum(unpack(t)) end

print(squaresumt{3, 5, 4, 1, 7})
sumOfSquares = function(seq)
    sum = 0
    for item in seq
        sum = sum + item*item
    end for
    return sum
end function

print sumOfSquares([4, 8, 15, 16, 23, 42])
print sumOfSquares([1, 2, 3, 4, 5])
print sumOfSquares([])
Temperature conversion
LuaMiniScript
function convert_temp(k)
    local c = k - 273.15
    local r = k * 1.8
    local f = r - 459.67
    return k, c, r, f
end

print(string.format([[
Kelvin: %.2f K
Celcius: %.2f °C
Rankine: %.2f °R
Fahrenheit: %.2f °F
]],convert_temp(21.0)))
fromKelvin = function(temp)
    print temp + " degrees in Kelvin is:"
    Celsius = temp - 273.15
    print Celsius + " degrees Celsius"
    Fahrenheit = round(Celsius  * 9/5 + 32,2)
    print Fahrenheit + " degrees Fahrenheit"
    Rankine = Fahrenheit + 459.67
    print Rankine + " degrees Rankine"
end function

temp = input("Enter a temperature in Kelvin: ")
fromKelvin temp.val
Text between
LuaMiniScript
function textbetween(text, sdelim, edelim)
  -- case #5 (end delimiter not present) is only problem for simplest approach, so preprocess:
  if not text:find(edelim=="end" and "$" or edelim) then edelim = "end" end
  -- then just:
  local re = (sdelim=="start" and "^" or sdelim) .. "(.-)" .. (edelim=="end" and "$" or edelim)
  return text:match(re) or ""
end

function test(text, sdelim, edelim, expected)
  print(textbetween(text, sdelim, edelim) == expected)
end

test( "Hello Rosetta Code world", "Hello ", " world", "Rosetta Code" )
test( "Hello Rosetta Code world", "start", " world", "Hello Rosetta Code" )
test( "Hello Rosetta Code world", "Hello ", "end", "Rosetta Code world" )
test( "</div><div style=\"french\">bonjour</div>", "<div style=\"french\">",
"</div>", "bonjour" )
test( "<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">",
"<text>", "<table>", "Hello <span>Rosetta Code</span> world</text><table
style=\"myTable\">" )
test( "<table style=\"myTable\"><tr><td>hello world</td></tr></table>",
"<table>", "</table>", "" )
test( "The quick brown fox jumps over the lazy other fox", "quick ", " fox", "brown" )
test( "One fish two fish red fish blue fish", "fish ", " red", "two fish" )
test( "FooBarBazFooBuxQuux", "Foo", "Foo", "BarBaz" )
textBetween = function(s, startDelim, endDelim)
    startPos = s.indexOf(startDelim) + startDelim.len
    if startDelim == "start" then startPos = 0
    endPos = s.indexOf(endDelim, startPos)
    if endDelim == "end" then endDelim = null
    return s[startPos:endPos]
end function

print textBetween("Hello Rosetta Code world", "Hello ", " world")
print textBetween("Hello Rosetta Code world", "start", " world")
print textBetween("Hello Rosetta Code world", "Hello ", "end")
print textBetween("The quick brown fox jumps over the lazy other fox", "quick ", " fox")
print textBetween("FooBarBazFooBuxQuux", "Foo", "Foo")
Textonyms
LuaMiniScript
-- Global variables
http = require("socket.http")
keys = {"VOICEMAIL", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
dictFile = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"

-- Return the sequence of keys required to type a given word
function keySequence (str)
    local sequence, noMatch, letter = ""
    for pos = 1, #str do
        letter = str:sub(pos, pos)
        for i, chars in pairs(keys) do
            noMatch = true
            if chars:match(letter) then
                sequence = sequence .. tostring(i)
                noMatch = false
                break
            end
        end
        if noMatch then return nil end
    end
    return tonumber(sequence)
end

-- Generate table of words grouped by key sequence
function textonyms (dict)
    local combTable, keySeq = {}
    for word in dict:gmatch("%S+") do
        keySeq = keySequence(word)
        if keySeq then
            if combTable[keySeq] then
                table.insert(combTable[keySeq], word)
            else
                combTable[keySeq] = {word}
            end
        end
    end
    return combTable
end

-- Analyse sequence table and print details
function showReport (keySeqs)
    local wordCount, seqCount, tCount = 0, 0, 0
    for seq, wordList in pairs(keySeqs) do
        wordCount = wordCount + #wordList
        seqCount = seqCount + 1
        if #wordList > 1 then tCount = tCount + 1 end
    end
    print("There are " .. wordCount .. " words in " .. dictFile)
    print("which can be represented by the digit key mapping.")
    print("They require " .. seqCount .. " digit combinations to represent them.")
    print(tCount .. " digit combinations represent Textonyms.")
end

-- Main procedure
showReport(textonyms(http.request(dictFile)))
import "listUtil"
import "mapUtil"

groups = "abc def ghi jkl mno pqrs tuv wxyz".split
charToNum = {}
for i in groups.indexes
	for ch in groups[i]
		charToNum[ch] = i + 2
	end for
end for

words = file.readLines("/sys/data/englishWords.txt")

wordToNum = function(word)
	parts = word.split("")
	parts.apply function(ch)
		return charToNum[ch]
	end function
	return parts.join("")
end function

numToWords = {}
moreThan1Word = 0
for word in words
	num = wordToNum(word.lower)
	if numToWords.hasIndex(num) then
		numToWords[num].push word
	else
		numToWords[num] = [word]
	end if
	if numToWords[num].len == 2 then moreThan1Word = moreThan1Word + 1
end for

print "There are " + words.len + " words in englishWords.txt which can be represented  by the digit
key mapping."
print "They require " + numToWords.len + " digit combinations to represent them."
print moreThan1Word + " digit combinations represent Textonyms."

while true
	print
	inp = input("Enter a word or digit combination: ")
	if not inp then break
	if val(inp) > 0 then
		print inp + " -> " + numToWords.get(inp)
	else
		num = wordToNum(inp.lower)
		print "Digit key combination for """ + inp + """ is: " + num
		print num + " -> " + numToWords.get(num)
	end if
end while
The Twelve Days of Christmas
LuaMiniScript
local days = {
    'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
    'tenth', 'eleventh', 'twelfth',
}

local gifts = {
    "A partridge in a pear tree",
    "Two turtle doves",
    "Three french hens",
    "Four calling birds",
    "Five golden rings",
    "Six geese a-laying",
    "Seven swans a-swimming",
    "Eight maids a-milking",
    "Nine ladies dancing",
    "Ten lords a-leaping",
    "Eleven pipers piping",
    "Twelve drummers drumming",
}

local verses = {}

for i = 1, 12 do
    local lines = {}
    lines[1] = "On the " .. days[i] .. " day of Christmas, my true love gave to me"
    
    local j = i
    local k = 2
    repeat
        lines[k] = gifts[j]
        k = k + 1
        j = j - 1
    until j == 0
    
    verses[i] = table.concat(lines, '\n')
end

print(table.concat(verses, '\n\n'))
days = ["first","second","third", "fourth","fifth","sixth",
        "seventh","eigth","nineth","tenth","eleventh","twelfth"]
gifts = ["A partridge in a pear tree.","Two turtle doves, and",
        "Three French hens,","Four calling birds,",
        "Five gold rings,","Six geese a-laying,",
        "Seven swans a-swimming,","Eight maids a-milking,",
        "Nine ladies dancing,","Ten lords a-leaping,",
        "Eleven pipers piping,","Twelve drummers drumming,"]

for i in range(0,11)
    print "On the " + days[i] + " day of Christmas,"
    print "my true love gave to me,"
    for j in range(i,0)
        print " " + gifts[j]
    end for
    print "     ----------"
end for
Time a function
LuaMiniScript
function Test_Function()
    for i = 1, 10000000 do
        local s = math.log( i )
        s = math.sqrt( s )
    end
end

t1 = os.clock()
    Test_Function()
t2 = os.clock()

print( os.difftime( t2, t1 ) )
start = time
for i in range(1,100000)
end for
duration = time - start
print "Process took " + duration + " seconds"
Tokenize a string
LuaMiniScript
function string:split (sep)
    local sep, fields = sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    self:gsub(pattern, function(c) fields[#fields+1] = c end)
    return fields
end

local str = "Hello,How,Are,You,Today"
print(table.concat(str:split(","), "."))
tokens = "Hello,How,Are,You,Today".split(",")
print tokens.join(".")
Towers of Hanoi
LuaMiniScript
function move(n, src, dst, via)
    if n > 0 then
        move(n - 1, src, via, dst)
        print(src, 'to', dst)
        move(n - 1, via, dst, src)
    end
end

move(4, 1, 2, 3)
moveDisc = function(n, A, C, B)
    if n == 0 then return
    moveDisc n-1, A, B, C
    print "Move disc " + n + " from pole " + A + " to pole " + C
    moveDisc n-1, B, C, A
end function

// Move disc 3 from pole 1 to pole 3, with pole 2 as spare
moveDisc 3, 1, 3, 2
Trigonometric functions
LuaMiniScript
print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))
pi3 = pi/3
degToRad = pi/180
print "sin PI/3 radians = " + sin(pi3)
print "sin 60 degrees = " + sin(60*degToRad)
print "arcsin 0.5 in radians = " + asin(0.5)
print "arcsin 0.5 in degrees = " + asin(0.5)/degToRad
print "cos PI/3 radians = " + cos(pi3)
print "cos 60 degrees = " + cos(60*degToRad)
print "arccos 0.5 in radians = " + acos(0.5)
print "arccos 0.5 in degrees = " + acos(0.5)/degToRad
print "tan PI/3 radians = " + tan(pi3)
print "tan 60 degrees = " + tan(60*degToRad)
print "arctan 0.5 in radians = " + atan(0.5)
print "arctan 0.5 in degrees = " + atan(0.5)/degToRad
Two sum
LuaMiniScript
function twoSum (numbers, sum)
    local i, j, s = 1, #numbers
    while i < j do
        s = numbers[i] + numbers[j]
        if s == sum then
            return {i, j}
        elseif s < sum then
            i = i + 1
        else
            j = j - 1
        end
    end
    return {}
end

print(table.concat(twoSum({0,2,11,19,90}, 21), ","))
twoSum = function(numbers, sum)
    // Make a map of values to their indices in the numbers array
    // as we go, so we will know when we've found a match.
    map = {}
    for i in numbers.indexes
        key = sum - numbers[i]
        if map.hasIndex(key) then return [map[key], i]
        map[numbers[i]] = i
    end for
end function

print twoSum([0, 2, 11, 19, 90], 21)
Vector
LuaMiniScript
vector = {mt = {}}

function vector.new (x, y)
    local new = {x = x or 0, y = y or 0}
    setmetatable(new, vector.mt)
    return new
end

function vector.mt.__add (v1, v2)
    return vector.new(v1.x + v2.x, v1.y + v2.y)
end

function vector.mt.__sub (v1, v2)
    return vector.new(v1.x - v2.x, v1.y - v2.y) 
end

function vector.mt.__mul (v, s)
    return vector.new(v.x * s, v.y * s)
end

function vector.mt.__div (v, s)
    return vector.new(v.x / s, v.y / s)
end

function vector.print (vec)    
    print("(" .. vec.x .. ", " .. vec.y .. ")")
end

local a, b = vector.new(5, 7), vector.new(2, 3)
vector.print(a + b)
vector.print(a - b)
vector.print(a * 11)
vector.print(a / 2)
vplus = function(v1, v2)
    return [v1[0]+v2[0],v1[1]+v2[1]]
end function

vminus = function (v1, v2)
    return [v1[0]-v2[0],v1[1]-v2[1]]
end function

vmult = function(v1, scalar)
    return [v1[0]*scalar, v1[1]*scalar]
end function

vdiv = function(v1, scalar)
    return [v1[0]/scalar, v1[1]/scalar]
end function

vector1 = [2,3]
vector2 = [4,5]

print vplus(vector1,vector2)
print vminus(vector2, vector1)
print vmult(vector1, 3)
print vdiv(vector2, 2)
Vector products
LuaMiniScript
Vector = {} 
function Vector.new( _x, _y, _z )
    return { x=_x, y=_y, z=_z }
end

function Vector.dot( A, B )
    return A.x*B.x + A.y*B.y + A.z*B.z
end

function Vector.cross( A, B )
    return { x = A.y*B.z - A.z*B.y,
             y = A.z*B.x - A.x*B.z,
             z = A.x*B.y - A.y*B.x }
end

function Vector.scalar_triple( A, B, C )
    return Vector.dot( A, Vector.cross( B, C ) )
end

function Vector.vector_triple( A, B, C )
    return Vector.cross( A, Vector.cross( B, C ) )
end


A = Vector.new( 3, 4, 5 )
B = Vector.new( 4, 3, 5 )
C = Vector.new( -5, -12, -13 )

print( Vector.dot( A, B ) )

r = Vector.cross(A, B )
print( r.x, r.y, r.z )

print( Vector.scalar_triple( A, B, C ) )

r = Vector.vector_triple( A, B, C )
print( r.x, r.y, r.z )
vectorA = [3, 4, 5]
vectorB = [4, 3, 5]
vectorC = [-5, -12, -13]

dotProduct = function(x, y)
    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
end function

crossProduct = function(x, y)
    return [x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2], x[0]*y[1] - x[1]*y[0]]
end function

print "Dot Product = " + dotProduct(vectorA, vectorB)
print "Cross Product = " + crossProduct(vectorA, vectorB)
print "Scalar Triple Product = " + dotProduct(vectorA, crossProduct(vectorB,vectorC))
print "Vector Triple Product = " + crossProduct(vectorA, crossProduct(vectorB,vectorC))
Word wrap
LuaMiniScript
function splittokens(s)
    local res = {}
    for w in s:gmatch("%S+") do
        res[#res+1] = w
    end
    return res
end

function textwrap(text, linewidth)
    if not linewidth then
        linewidth = 75
    end

    local spaceleft = linewidth
    local res = {}
    local line = {}

    for _, word in ipairs(splittokens(text)) do
        if #word + 1 > spaceleft then
            table.insert(res, table.concat(line, ' '))
            line = {word}
            spaceleft = linewidth - #word
        else
            table.insert(line, word)
            spaceleft = spaceleft - (#word + 1)
        end
    end

    table.insert(res, table.concat(line, ' '))
    return table.concat(res, '\n')
end

local example1 = [[
Even today, with proportional fonts and complex layouts,
there are still cases where you need to wrap text at a
specified column. The basic task is to wrap a paragraph
of text in a simple way in your language. If there is a
way to do this that is built-in, trivial, or provided in
a standard library, show that. Otherwise implement the
minimum length greedy algorithm from Wikipedia.
]]

print(textwrap(example1))
print()
print(textwrap(example1, 60))
str = "one two three four five six seven eight nine ten eleven!"
width = 15
words = str.split
pos = 0
line = ""
for word in words
    pos = pos + word.len + 1
    if pos <= width then
        line = line + word + " "
    else
        print line[:-1]
        line = word + " "
        pos = word.len
    end if
end for
print line[:-1]
Write language name in 3D ASCII
LuaMiniScript
io.write(" /$$\n")
io.write("| $$\n")
io.write("| $$       /$$   /$$  /$$$$$$\n")
io.write("| $$      | $$  | $$ |____  $$\n")
io.write("| $$      | $$  | $$  /$$$$$$$\n")
io.write("| $$      | $$  | $$ /$$__  $$\n")
io.write("| $$$$$$$$|  $$$$$$/|  $$$$$$$\n")
io.write("|________/ \______/  \_______/\n")
data = [
" ______  _____                       _________",
"|\     \/     \  ___  ________   ___|\   _____\ ________  ________  ___  ________  _________   ",
"\ \   _ \  _   \|\  \|\   ___  \|\  \ \  \____||\   ____\|\   ____\|\  \|\   __  \|\___   ___\ ",
" \ \  \\\__\ \  \ \  \ \  \\ \  \ \  \ \_____  \ \  \___|\ \  \___|\ \  \ \  \|\  \|___ \  \_| ",
"  \ \  \\|__| \  \ \  \ \  \\ \  \ \  \|____|\  \ \  \    \ \  \    \ \  \ \   ____\   \ \  \  ",
"   \ \  \    \ \  \ \  \ \  \\ \  \ \  \____\_\  \ \  \____\ \  \    \ \  \ \  \___|    \ \  \ ",
"    \ \__\    \ \__\ \__\ \__\\ \__\ \__\_________\ \_______\ \__\    \ \__\ \__\        \ \__\",
"     \|__|     \|__|\|__|\|__| \|__|\|__||________|\|_______|\|__|     \|__|\|__|         \|__|"]

for line in data
    print line
end for
Zero to the zero power
LuaMiniScript
print(0^0)
print "The result of zero to the zero power is " + 0^0