Skip to content

Instantly share code, notes, and snippets.

@buckle2000
Created February 28, 2017 08:00
Show Gist options
  • Save buckle2000/424648a83f643ed81ac0e7c8e98c6e0c to your computer and use it in GitHub Desktop.
Save buckle2000/424648a83f643ed81ac0e7c8e98c6e0c to your computer and use it in GitHub Desktop.
lua helper functions
iter_helper = (t, index) ->
index += 1
if index == t.n
return
return index, t[index]
class Array
new: =>
@n = 0
@from_pack = (...) ->
arr = @!
arr.n = select('#', ...)
for i=1,arr.n
arr[i-1] = select(i, ...)
arr
@from_table = (t) ->
arr = @!
arr.n = table.maxn(t)
for i=1,arr.n
arr[i-1] = t[i]
arr
@from_range = (head,tail) ->
arr = @!
for i=head,tail
arr\push i
arr
@from_default = (size, default_value) ->
arr = @!
if default_value ~= nil
for i=0,size-1
arr[i] = default_value
arr.n = size
arr
insert: (pos, value) =>
for i=@n-1,pos,-1
@[i+1] = @[i]
@[pos] = value
@n += 1
return
remove: (pos) =>
assert pos >= 0 and pos < @n,
"Index out of bounds. #{pos}"
@n -= 1
value = @[pos]
for i=pos,@n
@[i] = @[i+1]
value
push: (value) =>
@n += 1
@[@n-1] = value
return
pop: =>
value = @[@n]
@[@n] = nil
@n -= 1
value
iter: =>
iter_helper, @, -1
maxn: =>
@n
concat: =>
-- TODO
sort: =>
-- TODO
-- __index: (index) =>
-- assert(0 <= index and index < @n,
-- "Index out of bounds. #{index}")
-- rawget @, index
-- __newindex: (index, v) =>
-- if index == @n
-- @n += 1
-- rawset @, index, v
-- else
-- assert(0 <= index and index < @n,
-- "Index out of bounds. #{index}")
-- nil
__tostring: =>
if @n == 0
"{}"
else
values = tostring(@[0])
for i=1,@n-1
values ..= "," .. tostring(@[i])
"{#{values}} #{@n}"
Array = require "array"
class Array2D
-- not auto init
new: (@w, @h) =>
@size = w * h
@data = Array.from_default size
index: (x, y) =>
x + @w * y
get: (x, y) =>
@data[@index(x, y)]
set: (x, y, value) =>
@data[@index(x, y)] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment