From d90bd710132d07e35e873609c5bb522624b88fd5 Mon Sep 17 00:00:00 2001 From: leaf corcoran Date: Mon, 12 Dec 2011 00:49:06 -0800 Subject: [PATCH] updated doc html --- docs/reference_manual.html | 1573 +++++++++++++++++++++++++----------- docs/standard_lib.html | 476 +++++++++++ 2 files changed, 1574 insertions(+), 475 deletions(-) create mode 100644 docs/standard_lib.html diff --git a/docs/reference_manual.html b/docs/reference_manual.html index 82f1c01..d768d16 100644 --- a/docs/reference_manual.html +++ b/docs/reference_manual.html @@ -1,9 +1,9 @@ - + - MoonScript v0.2.0 + MoonScript v0.2.0 - Language Guide
-

MoonScript v0.2.0

+

MoonScript v0.2.0 - Language Guide

- + +
+ + +
+

All Pages

+ +
+
+

MoonScript is a programming language that compiles to Lua. This guide expects the reader to have basic @@ -250,33 +311,45 @@ already defined will be declared as local to the scope of that declaration. If you wish to create a global variable it must be done using the export keyword.

-
moonscriptlua
hello = "world"
-a,b,c = 1, 2, 3
-
local hello = "world"
-local a, b, c = 1, 2, 3
+ + + + +
moonscriptlua
hello = "world"
+a,b,c = 1, 2, 3
local hello = "world"
+local a, b, c = 1, 2, 3
+

Update Assignment

+=, -=, /=, *=, %=, ..= operators have been added for updating a value by a certain amount. They are aliases for their expanded equivalents.

- +
moonscriptlua
x = 0
+
+
+
+
moonscriptlua
x = 0
 x += 10
 
 s = "hello "
-s ..= "world"
-
local x = 0
+s ..= "world"
local x = 0
 x = x + 10
 local s = "hello "
-s = s .. "world"
+s = s .. "world"
+

Comments

Like Lua, comments start with -- and continue to the end of the line. Comments are not written to the output.

-
moonscriptlua
-- I am a comment
-
+ + + + +
moonscriptlua
-- I am a comment
+

Literals & Operators

@@ -291,21 +364,27 @@ syntax. This applies to numbers, strings, booleans, and nil.

All functions are created using a function expression. A simple function is denoted using the arrow: ->

- +
moonscriptlua
my_function = ->
-my_function() -- call the empty function
-
local my_function
+
+
+
+
moonscriptlua
my_function = ->
+my_function() -- call the empty function
local my_function
 my_function = function() end
-my_function()
+my_function()
+

The body of the function can either be one statement placed directly after the arrow, or it can be a series of statements indented on the following lines:

- +
moonscriptlua
func_a = -> print "hello world"
+
+
+
+
moonscriptlua
func_a = -> print "hello world"
 
 func_b = ->
   value = 100
-  print "The value:", value
-
local func_a
+  print "The value:", value
local func_a
 func_a = function()
   return print("hello world")
 end
@@ -313,74 +392,104 @@ arrow, or it can be a series of statements indented on the following lines:

func_b = function() local value = 100 return print("The value:", value) -end
+end
+

If a function has no arguments, it can be called using the ! operator, instead of empty parentheses. The ! invocation is the preferred way to call functions with no arguments.

-
moonscriptlua
func_a!
-func_b()
-
func_a()
-func_b()
+ + + + +
moonscriptlua
func_a!
+func_b()
func_a()
+func_b()
+

Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses:

- +
moonscriptlua
sum = (x, y) -> print "sum", x + y
-
local sum
+
+
+
+
moonscriptlua
sum = (x, y) -> print "sum", x + y
local sum
 sum = function(x, y)
   return print("sum", x + y)
-end
+end
+

Functions can be called by listing the values of the arguments after the name of the variable where the function is stored. When chaining together function calls, the arguments are applied to the closest function to the left.

- +
moonscriptlua
sum 10, 20
+
+
+
+
moonscriptlua
sum 10, 20
 print sum 10, 20
 
-a b c "a", "b", "c"
-
sum(10, 20)
+a b c "a", "b", "c"
sum(10, 20)
 print(sum(10, 20))
-a(b(c("a", "b", "c")))
+a(b(c("a", "b", "c")))
+

In order to avoid ambiguity in when calling functions, parentheses can also be used to surround the arguments. This is required here in order to make sure the right arguments get sent to the right functions.

-
moonscriptlua
print "x:", sum(10, 20), "y:", sum(30, 40)
-
print("x:", sum(10, 20), "y:", sum(30, 40))
+ + + + +
moonscriptlua
print "x:", sum(10, 20), "y:", sum(30, 40)
print("x:", sum(10, 20), "y:", sum(30, 40))
+

Functions will coerce the last statement in their body into a return statement, this is called implicit return:

- +
moonscriptlua
sum = (x, y) -> x + y
-print "The sum is ", sum 10, 20
-
local sum
+
+
+
+
moonscriptlua
sum = (x, y) -> x + y
+print "The sum is ", sum 10, 20
local sum
 sum = function(x, y)
   return x + y
 end
-print("The sum is ", sum(10, 20))
+print("The sum is ", sum(10, 20))
+

And if you need to explicitly return, you can use the return keyword:

- +
moonscriptlua
sum = (x, y) -> return x + y
-
local sum
+
+
+
+
moonscriptlua
sum = (x, y) -> return x + y
local sum
 sum = function(x, y)
   return x + y
-end
+end
+

Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas:

- +
moonscriptlua
mystery = (x, y) -> x + y, x - y
-a,b = mystery 10, 20
-
local mystery
+
+
+
+
moonscriptlua
mystery = (x, y) -> x + y, x - y
+a,b = mystery 10, 20
local mystery
 mystery = function(x, y)
   return x + y, x - y
 end
-local a, b = mystery(10, 20)
+local a, b = mystery(10, 20)
+

Fat Arrows

@@ -388,11 +497,15 @@ be a list of values separated by commas:

calling a method, a special syntax is provided for creating functions which automatically includes a self argument.

- +
moonscriptlua
func = (num) => self.value + num
-
local func
+
+
+
+
moonscriptlua
func = (num) => self.value + num
local func
 func = function(self, num)
   return self.value + num
-end
+end
+

Argument Defaults

@@ -400,10 +513,12 @@ automatically includes a self argument.

argument is determined to be empty if it’s value is nil. Any nil arguments that have a default value will be replace before the body of the function is run.

- +
moonscriptlua
my_function = (name="something", height=100) ->
+
+
+
+
moonscriptlua
my_function = (name="something", height=100) ->
   print "Hello I am", name
-  print "My height is", height
-
local my_function
+  print "My height is", height
local my_function
 my_function = function(name, height)
   if name == nil then
     name = "something"
@@ -413,15 +528,19 @@ that have a default value will be replace before the body of the function is run
   end
   print("Hello I am", name)
   return print("My height is", height)
-end
+end
+

An argument default value expression is evaluated in the body of the function in the order of the argument declarations. For this reason default values have access to previously declared arguments.

- +
moonscriptlua
some_args = (x=100, y=x+1000) ->
-  print x + y
-
local some_args
+
+
+
+
moonscriptlua
some_args = (x=100, y=x+1000) ->
+  print x + y
local some_args
 some_args = function(x, y)
   if x == nil then
     x = 100
@@ -430,7 +549,9 @@ access to previously declared arguments.

y = x + 1000 end return print(x + y) -end
+end
+

Considerations

@@ -443,12 +564,16 @@ subtraction operator. In order to force subtraction a space must be placed after the - operator. In order to force a negation, no space must follow the -. Consider the examples below.

- +
moonscriptlua
a = x - 10
+
+
+
+
moonscriptlua
a = x - 10
 b = x-10
-c = x -y
-
local a = x - 10
+c = x -y
local a = x - 10
 local b = x(-10)
-local c = x(-y)
+local c = x(-y)
+

The precedence of the first argument of a function call can also be controlled using whitespace if the argument is a literal string.In Lua, it is common to @@ -462,10 +587,14 @@ arguments can be passed to the function when it is called this way.

call acts as show above. The string literal belongs to any following expressions (if they exist), which serves as the argument list.

-
moonscriptlua
x = func"hello" + 100
-y = func "hello" + 100
-
local x = func("hello") + 100
-local y = func("hello" + 100)
+ + + + +
moonscriptlua
x = func"hello" + 100
+y = func "hello" + 100
local x = func("hello") + 100
+local y = func("hello" + 100)
+

Multi-line arguments

@@ -479,35 +608,45 @@ must end in a comma. And the following line must be indented more than the current indentation. Once indented, all other argument lines must be at the same level of indentation to be part of the argument list

- + +
moonscriptlua
my_func 5,4,3,
+
+
+
moonscriptlua
my_func 5,4,3,
   8,9,10
 
 cool_func 1,2,
   3,4,
   5,6,
-  7,8
-
my_func(5, 4, 3, 8, 9, 10)
-cool_func(1, 2, 3, 4, 5, 6, 7, 8)
+ 7,8
my_func(5, 4, 3, 8, 9, 10)
+cool_func(1, 2, 3, 4, 5, 6, 7, 8)
+

This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to.

- + +
moonscriptlua
my_func 5,6,7,
+
+
+
moonscriptlua
my_func 5,6,7,
   6, another_func 6,7,8,
     9,1,2,
-  5,4
-
my_func(5, 6, 7, 6, another_func(6, 7, 8, 9, 1, 2), 5, 4)
+ 5,4
my_func(5, 6, 7, 6, another_func(6, 7, 8, 9, 1, 2), 5, 4)
+

Because tables also use the comma as a delimiter, this indentation syntax is helpful for letting values be part of the argument list instead of being part of the table.

- +
moonscriptlua
x = {
+
+
+
+
moonscriptlua
x = {
   1,2,3,4, a_func 4,5,
     5,6,
   8,9,10
-}
-
local x = {
+}
local x = {
   1,
   2,
   3,
@@ -516,27 +655,35 @@ instead of being part of the table.

8, 9, 10 -}
+}
+

Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation futher on.

- +
moonscriptlua
y = { my_func 1,2,3,
+
+
+
+
moonscriptlua
y = { my_func 1,2,3,
    4,5,
   5,6,7
-}
-
local y = {
+}
local y = {
   my_func(1, 2, 3, 4, 5),
   5,
   6,
   7
-}
+}
+

The same thing can be done with other block level statements like conditionals. We can use indentation level to determine what statement a value belongs to:

- +
moonscriptlua
if func 1,2,3,
+
+
+
+
moonscriptlua
if func 1,2,3,
   "hello",
   "world"
     print "hello"
@@ -546,67 +693,83 @@ statement a value belongs to:

"hello", "world" print "hello" - print "I am inside if" -
if func(1, 2, 3, "hello", "world") then
+  print "I am inside if"
if func(1, 2, 3, "hello", "world") then
   print("hello")
   print("I am inside if")
 end
 if func(1, 2, 3, "hello", "world") then
   print("hello")
   print("I am inside if")
-end
+end
+

Table Literals

Like in Lua, tables are delimited in curly braces.

- +
moonscriptlua
some_values = { 1, 2, 3, 4 }
-
local some_values = {
+
+
+
+
moonscriptlua
some_values = { 1, 2, 3, 4 }
local some_values = {
   1,
   2,
   3,
   4
-}
+}
+

Unlike Lua, assigning a value to a key in a table is done with : (instead of =).

- +
moonscriptlua
some_values = {
+
+
+
+
moonscriptlua
some_values = {
   name: "Bill",
   age: 200,
   ["favorite food"]: "rice"
-}
-
local some_values = {
+}
local some_values = {
   name = "Bill",
   age = 200,
   ["favorite food"] = "rice"
-}
+}
+

The curly braces can be left off if a single table of key value pairs is being assigned.

- +
moonscriptlua
profile =
+
+
+
+
moonscriptlua
profile = 
   height: "4 feet",
   shoe_size: 13,
-  favorite_foods: {"ice cream", "donuts"}
-
local profile = {
+  favorite_foods: {"ice cream", "donuts"}
local profile = {
   height = "4 feet",
   shoe_size = 13,
   favorite_foods = {
     "ice cream",
     "donuts"
   }
-}
+}
+

Newlines can be used to delimit values instead of a comma (or both):

- +
moonscriptlua
values = {
+
+
+
+
moonscriptlua
values = {
   1,2,3,4
   5,6,7,8
   name: "superman"
   occupation: "crime fighting"
-}
-
local values = {
+}
local values = {
   1,
   2,
   3,
@@ -617,15 +780,19 @@ assigned.

8, name = "superman", occupation = "crime fighting" -}
+}
+

When creating a single line table literal, the curly braces can also be left off:

- +
moonscriptlua
my_function dance: "Tango", partner: "none"
+
+
+
+
moonscriptlua
my_function dance: "Tango", partner: "none"
 
-y = type: "dog", legs: 4, tails: 1
-
my_function({
+y = type: "dog", legs: 4, tails: 1
my_function({
   dance = "Tango",
   partner = "none"
 })
@@ -633,28 +800,36 @@ off:

type = "dog", legs = 4, tails = 1 -}
+}
+

The keys of a table literal can be language keywords without being escaped:

- +
moonscriptlua
tbl = {
+
+
+
+
moonscriptlua
tbl = {
   do: "something"
   end: "hunger"
-}
-
local tbl = {
+}
local tbl = {
   ["do"] = "something",
   ["end"] = "hunger"
-}
+}
+

If you are constructing a table out of variables and wish the keys to be the same as the variable names, then the : prefix operator can be used:

- +
moonscriptlua
hair = "golden"
+
+
+
+
moonscriptlua
hair = "golden"
 height = 200
 person = { :hair, :height, shoe_size: 40 }
 
-print_table :hair, :height
-
local hair = "golden"
+print_table :hair, :height
local hair = "golden"
 local height = 200
 local person = {
   hair = hair,
@@ -664,19 +839,29 @@ same as the variable names, then the : prefix operator can be used:
 print_table({
   hair = hair,
   height = height
-})
+})
-

Table Comprehensions

-

Table comprehensions provide a quick way to iterate over a table’s values while -applying a statement and accumulating the result.

+

Comprehensions

+ +

Compiling provide a convenient syntax for constructing a new table by iterating +over some existing object and applying an expression to its values. There are +two kinds of comprehensions: list comprehensions and table comprehensions. They +both produce Lua tables; list comprehensions accumulate values into an +array-like table, and table comprehensions let you set both the key and the +value on each iteration.

+ +

List Comprehensions

The following creates a copy of the items table but with all the values doubled.

- +
moonscriptlua
items = { 1, 2, 3, 4 }
-doubled = [item * 2 for i, item in ipairs items]
-
local items = {
+
+
+
+
moonscriptlua
items = { 1, 2, 3, 4 }
+doubled = [item * 2 for i, item in ipairs items]
local items = {
   1,
   2,
   3,
@@ -690,13 +875,17 @@ doubled.

_accum_0[_len_0] = item * 2 end return _accum_0 -end)()
+end)()
+

The items included in the new table can be restricted with a when clause:

- +
moonscriptlua
iter = ipairs items
-slice = [item for i, item in iter when i > 1 and i < 3]
-
local iter = ipairs(items)
+
+
+
+
moonscriptlua
iter = ipairs items
+slice = [item for i, item in iter when i > 1 and i < 3]
local iter = ipairs(items)
 local slice = (function()
   local _accum_0 = { }
   local _len_0 = 0
@@ -707,36 +896,42 @@ doubled.

end end return _accum_0 -end)()
+end)()
+

Because it is common to iterate over the values of a numerically indexed table, an * operator is introduced. The doubled example can be rewritten as:

- +
moonscriptlua
doubled = [item * 2 for item in *items]
-
local doubled = (function()
+
+
+
+
moonscriptlua
doubled = [item * 2 for item in *items]
local doubled = (function()
   local _accum_0 = { }
   local _len_0 = 0
-  do
-    local _item_0 = items
-    for _index_0 = 1, #_item_0 do
-      local item = _item_0[_index_0]
-      _len_0 = _len_0 + 1
-      _accum_0[_len_0] = item * 2
-    end
+  local _list_0 = items
+  for _index_0 = 1, #_list_0 do
+    local item = _list_0[_index_0]
+    _len_0 = _len_0 + 1
+    _accum_0[_len_0] = item * 2
   end
   return _accum_0
-end)()
+end)()
+

The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause.

Using multiple for clauses is the same as using nested loops:

- +
moonscriptlua
x_coords = {4, 5, 6, 7}
+
+
+
+
moonscriptlua
x_coords = {4, 5, 6, 7}
 y_coords = {9, 2, 3}
 
-points = [{x,y} for x in *x_coords for y in *y_coords]
-
local x_coords = {
+points = [{x,y} for x in *x_coords for y in *y_coords]
local x_coords = {
   4,
   5,
   6,
@@ -750,25 +945,98 @@ requirement is that a comprehension has at least one for clause.

local points = (function() local _accum_0 = { } local _len_0 = 0 - do - local _item_0 = x_coords - for _index_0 = 1, #_item_0 do - local x = _item_0[_index_0] - do - local _item_1 = y_coords - for _index_1 = 1, #_item_1 do - local y = _item_1[_index_1] - _len_0 = _len_0 + 1 - _accum_0[_len_0] = { - x, - y - } - end - end + local _list_0 = x_coords + for _index_0 = 1, #_list_0 do + local x = _list_0[_index_0] + local _list_1 = y_coords + for _index_0 = 1, #_list_1 do + local y = _list_1[_index_0] + _len_0 = _len_0 + 1 + _accum_0[_len_0] = { + x, + y + } end end return _accum_0 -end)()
+end)()
+ + +

Table Comprehensions

+ +

The syntax for table comprehensions is very similar, differing by using { and +} and taking two values from each iteration.

+ +

This example copies the key-value table thing:

+ + + + + +
moonscriptlua
thing = {
+  color: "red"
+  name: "fast"
+  width: 123
+}
+
+thing_copy = {k,v for k,v in pairs thing}
local thing = {
+  color = "red",
+  name = "fast",
+  width = 123
+}
+local thing_copy = (function()
+  local _tbl_0 = { }
+  for k, v in pairs(thing) do
+    _tbl_0[k] = v
+  end
+  return _tbl_0
+end)()
+ + +

Table comprehensions, like list comprehensions, also support multiple for and +when clauses. In this example we use a where clause to prevent the value +associated with the color key from being copied.

+ + + + + +
moonscriptlua
no_color = {k,v for k,v in pairs thing when k != "color"}
local no_color = (function()
+  local _tbl_0 = { }
+  for k, v in pairs(thing) do
+    if k ~= "color" then
+      _tbl_0[k] = v
+    end
+  end
+  return _tbl_0
+end)()
+ + +

The * operator is also supported. Here we create a square root look up table +for a few numbers.

+ + + + + +
moonscriptlua
numbers = {1,2,3,4}
+sqrts = {i, math.sqrt i for i in *numbers}
local numbers = {
+  1,
+  2,
+  3,
+  4
+}
+local sqrts = (function()
+  local _tbl_0 = { }
+  local _list_0 = numbers
+  for _index_0 = 1, #_list_0 do
+    local i = _list_0[_index_0]
+    _tbl_0[i] = math.sqrt(i)
+  end
+  return _tbl_0
+end)()
+

Slicing

@@ -779,73 +1047,81 @@ a step size in a for loop.

Here we can set the minimum and maximum bounds, taking all items with indexes between 1 and 5 inclusive:

- +
moonscriptlua
slice = [item for item in *items[1:5]]
-
local slice = (function()
+
+
+
+
moonscriptlua
slice = [item for item in *items[1,5]]
local slice = (function()
   local _accum_0 = { }
   local _len_0 = 0
-  do
-    local _max_0 = 5
-    local _item_0 = items
-    for _index_0 = 1, _max_0 < 0 and #_item_0 + _max_0 or _max_0 do
-      local item = _item_0[_index_0]
-      _len_0 = _len_0 + 1
-      _accum_0[_len_0] = item
-    end
+  local _list_0 = items
+  local _max_0 = 5
+  for _index_0 = 1, _max_0 < 0 and #_list_0 + _max_0 or _max_0 do
+    local item = _list_0[_index_0]
+    _len_0 = _len_0 + 1
+    _accum_0[_len_0] = item
   end
   return _accum_0
-end)()
+end)()
+

Any of the slice arguments can be left off to use a sensible default. In this example, if the max index is left off it defaults to the length of the table. This will take everything but the first element:

- +
moonscriptlua
slice = [item for item in *items[2:]]
-
local slice = (function()
+
+
+
+
moonscriptlua
slice = [item for item in *items[2,]]
local slice = (function()
   local _accum_0 = { }
   local _len_0 = 0
-  do
-    local _item_0 = items
-    for _index_0 = 2, #_item_0 do
-      local item = _item_0[_index_0]
-      _len_0 = _len_0 + 1
-      _accum_0[_len_0] = item
-    end
+  local _list_0 = items
+  for _index_0 = 2, #_list_0 do
+    local item = _list_0[_index_0]
+    _len_0 = _len_0 + 1
+    _accum_0[_len_0] = item
   end
   return _accum_0
-end)()
+end)()
+

If the minimum bound is left out, it defaults to 1. Here we only provide a step size and leave the other bounds blank. This takes all odd indexed items: (1, 3, 5, …)

- +
moonscriptlua
slice = [item for items in *items[::2]]
-
local slice = (function()
+
+
+
+
moonscriptlua
slice = [item for items in *items[,,2]]
local slice = (function()
   local _accum_0 = { }
   local _len_0 = 0
-  do
-    local _item_0 = items
-    for _index_0 = 1, #_item_0, 2 do
-      local items = _item_0[_index_0]
-      _len_0 = _len_0 + 1
-      _accum_0[_len_0] = item
-    end
+  local _list_0 = items
+  for _index_0 = 1, #_list_0, 2 do
+    local items = _list_0[_index_0]
+    _len_0 = _len_0 + 1
+    _accum_0[_len_0] = item
   end
   return _accum_0
-end)()
+end)()
+

For Loop

There are two for loop forms, just like in Lua. A numeric one and a generic one:

- +
moonscriptlua
for i = 10, 20
+
+
+
+
moonscriptlua
for i = 10, 20
   print i
 
 for k = 1,15,2 -- an optional step provided
   print k 
 
 for key, value in pairs object
-  print key, value
-
for i = 10, 20 do
+  print key, value
for i = 10, 20 do
   print(i)
 end
 for k = 1, 15, 2 do
@@ -853,37 +1129,43 @@ size and leave the other bounds blank. This takes all odd indexed items: (1, 3,
 end
 for key, value in pairs(object) do
   print(key, value)
-end
+end
+

The slicing and * operators can be used, just like with table comprehensions:

-
moonscriptlua
for item in *items[2:4]
-  print item
-
do
-  local _max_0 = 4
-  local _item_0 = items
-  for _index_0 = 2, _max_0 < 0 and #_item_0 + _max_0 or _max_0 do
-    local item = _item_0[_index_0]
-    print(item)
-  end
-end
+ + + + +
moonscriptlua
for item in *items[2,4]
+  print item
local _list_0 = items
+local _max_0 = 4
+for _index_0 = 2, _max_0 < 0 and #_list_0 + _max_0 or _max_0 do
+  local item = _list_0[_index_0]
+  print(item)
+end
+

A shorter syntax is also available for all variations when the body is only a single line:

- +
moonscriptlua
for item in *items do print item
+
+
+
+
moonscriptlua
for item in *items do print item
 
-for j = 1,10,3 do print j
-
do
-  local _item_0 = items
-  for _index_0 = 1, #_item_0 do
-    local item = _item_0[_index_0]
-    print(item)
-  end
+for j = 1,10,3 do print j
local _list_0 = items
+for _index_0 = 1, #_list_0 do
+  local item = _list_0[_index_0]
+  print(item)
 end
 for j = 1, 10, 3 do
   print(j)
-end
+end
+

A for loop can also be used an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating @@ -891,12 +1173,14 @@ table if the value of that expression is not nil.

Doubling every even number:

- +
moonscriptlua
doubled_evens = for i=1,20
+
+
+
+
moonscriptlua
doubled_evens = for i=1,20
   if i % 2 == 0
     i * 2
   else
-    i
-
local doubled_evens = (function()
+    i
local doubled_evens = (function()
   local _accum_0 = { }
   local _len_0 = 0
   for i = 1, 20 do
@@ -912,14 +1196,18 @@ table if the value of that expression is not nil.

end end return _accum_0 -end)()
+end)()
+

Filtering out odd numbers:

- +
moonscriptlua
my_numbers = {1,2,3,4,5,6}
+
+
+
+
moonscriptlua
my_numbers = {1,2,3,4,5,6}
 odds = for x in *my_numbers
-  if x % 2 == 1 then x
-
local my_numbers = {
+  if x % 2 == 1 then x
local my_numbers = {
   1,
   2,
   3,
@@ -930,34 +1218,36 @@ table if the value of that expression is not nil.

local odds = (function() local _accum_0 = { } local _len_0 = 0 - do - local _item_0 = my_numbers - for _index_0 = 1, #_item_0 do - local x = _item_0[_index_0] - local _value_0 - if x % 2 == 1 then - _value_0 = x - end - if _value_0 ~= nil then - _len_0 = _len_0 + 1 - _accum_0[_len_0] = _value_0 - end + local _list_0 = my_numbers + for _index_0 = 1, #_list_0 do + local x = _list_0[_index_0] + local _value_0 + if x % 2 == 1 then + _value_0 = x + end + if _value_0 ~= nil then + _len_0 = _len_0 + 1 + _accum_0[_len_0] = _value_0 end end return _accum_0 -end)()
+end)()
+

For loops at the end of a function body are not accumulated into a table for a return value (Instead the function will return nil). Either an explicit return statement can be used, or the loop can be converted into a list comprehension.

- +
moonscriptlua
func_a = -> for i=1,10 do i
+
+
+
+
moonscriptlua
func_a = -> for i=1,10 do i
 func_b = -> return for i=1,10 do i
 
 print func_a! -- prints nil
-print func_b! -- prints table object
-
local func_a
+print func_b! -- prints table object
local func_a
 func_a = function()
   for i = 1, 10 do
     local _ = i
@@ -979,7 +1269,9 @@ comprehension.

end)() end print(func_a()) -print(func_b())
+print(func_b())
+

This is done to avoid the needless creation of tables for functions that don’t need to return the results of the loop.

@@ -988,20 +1280,24 @@ need to return the results of the loop.

The while loop also comes in two variations:

- +
moonscriptlua
i = 10
+
+
+
+
moonscriptlua
i = 10
 while i > 0
   print i
   i -= 1
 
-while running == true do my_function!
-
local i = 10
+while running == true do my_function!
local i = 10
 while i > 0 do
   print(i)
   i = i - 1
 end
 while running == true do
   my_function()
-end
+end
+

Like for loops, the while loop can also be used an expression. Additionally, for a function to return the accumulated value of a while loop, the statement @@ -1009,45 +1305,59 @@ must be explicitly returned.

Conditionals

- +
moonscriptlua
have_coins = false
+
+
+
+
moonscriptlua
have_coins = false
 if have_coins
   print "Got coins"
 else
-  print "No coins"
-
local have_coins = false
+  print "No coins"
local have_coins = false
 if have_coins then
   print("Got coins")
 else
   print("No coins")
-end
+end
+

A short syntax for single statements can also be used:

- +
moonscriptlua
have_coins = false
-if have_coins then print "Got coins" else print "No coins"
-
local have_coins = false
+
+
+
+
moonscriptlua
have_coins = false
+if have_coins then print "Got coins" else print "No coins"
local have_coins = false
 if have_coins then
   print("Got coins")
 else
   print("No coins")
-end
+end
+

Because if statements can be used as expressions, this can able be written as:

- +
moonscriptlua
have_coins = false
-print if have_coins then "Got coins" else "No coins"
-
local have_coins = false
+
+
+
+
moonscriptlua
have_coins = false
+print if have_coins then "Got coins" else "No coins"
local have_coins = false
 print((function()
   if have_coins then
     return "Got coins"
   else
     return "No coins"
   end
-end)())
+end)())
+

Conditionals can also be used in return statements and assignments:

- +
moonscriptlua
is_tall = (name) ->
+
+
+
+
moonscriptlua
is_tall = (name) ->
   if name == "Rob"
     true
   else
@@ -1058,8 +1368,8 @@ must be explicitly returned.

else "I am not so tall" -print message -- prints: I am very tall -
local is_tall
+print message -- prints: I am very tall
local is_tall
 is_tall = function(name)
   if name == "Rob" then
     return true
@@ -1073,28 +1383,117 @@ must be explicitly returned.

else message = "I am not so tall" end -print(message)
+print(message)
+

Line Decorators

For convenience, the for loop and if statement can be applied to single statements at the end of the line:

- +
moonscriptlua
print "hello world" if name == "Rob"
-
if name == "Rob" then
+
+
+
+
moonscriptlua
print "hello world" if name == "Rob"
if name == "Rob" then
   print("hello world")
-end
+end
+

And with basic loops:

-
moonscriptlua
print "item: ", item for item in *items
-
do
-  local _item_0 = items
-  for _index_0 = 1, #_item_0 do
-    local item = _item_0[_index_0]
-    print("item: ", item)
-  end
-end
+ + + + +
moonscriptlua
print "item: ", item for item in *items
local _list_0 = items
+for _index_0 = 1, #_list_0 do
+  local item = _list_0[_index_0]
+  print("item: ", item)
+end
+ + +

Switch

+ +

The switch statement is shorthand for writing a series of if statements that +check against the same value. Note that the value is only evaluated once. Like +if statements, switches can have an else block to handle no matches. Comparison +is done with the == operator.

+ + + + + +
moonscriptlua
name = "Dan"
+switch name
+  when "Robert"
+    print "You are robert"
+  when "Dan"
+    print "Your name, it's Dan"
+  else
+    print "I don't know about your name"
local name = "Dan"
+local _exp_0 = name
+if "Robert" == _exp_0 then
+  print("You are robert")
+elseif "Dan" == _exp_0 then
+  print("Your name, it's Dan")
+else
+  print("I don't know about your name")
+end
+ + +

Switches can be used as expressions as well, here we can assign the result of +the switch to a variable:

+ + + + + +
moonscriptlua
b = 1
+next_number = switch b
+  when 1
+    2
+  when 2
+    3
+  else
+    error "can't count that high!"
local b = 1
+local next_number
+local _exp_0 = b
+if 1 == _exp_0 then
+  next_number = 2
+elseif 2 == _exp_0 then
+  next_number = 3
+else
+  next_number = error("can't count that high!")
+end
+ + +

We can use the then keyword to write a switch’s when block on a single line. +No extra keyword is needed to write the else block on a single line.

+ + + + + +
moonscriptlua
msg = switch math.random(1, 5)
+  when 1 then "you are lucky"
+  when 2 then "you are almost lucky"
+  else "not so lucky"
local msg
+local _exp_0 = math.random(1, 5)
+if 1 == _exp_0 then
+  msg = "you are lucky"
+elseif 2 == _exp_0 then
+  msg = "you are almost lucky"
+else
+  msg = "not so lucky"
+end
+ + +

It is worth noting the order of the case comparison expression. The case’s +expression is on the left hand side. This can be useful if the case’s +expression wants to overwrite how the comparison is done by defining an eq +metamethod.

Object Oriented Programming

@@ -1104,7 +1503,9 @@ code if you wish to know the implementation details.

A simple class:

- +
moonscriptlua
class Inventory
+
+
+
+
moonscriptlua
class Inventory
   new: =>
     @items = {}
 
@@ -1112,9 +1513,10 @@ code if you wish to know the implementation details.

if @items[name] @items[name] += 1 else - @items[name] = 1 -
local Inventory
-Inventory = (function(_parent_0)
+      @items[name] = 1
local Inventory
+Inventory = (function()
+  local _parent_0 = nil
   local _base_0 = {
     add_item = function(self, name)
       if self.items[name] then
@@ -1127,23 +1529,35 @@ code if you wish to know the implementation details.

} _base_0.__index = _base_0 if _parent_0 then - setmetatable(_base_0, getmetatable(_parent_0).__index) + setmetatable(_base_0, _parent_0.__base) end local _class_0 = setmetatable({ __init = function(self) self.items = { } - end + end, + __base = _base_0, + __name = "Inventory", + __parent = _parent_0 }, { - __index = _base_0, - __call = function(mt, ...) - local self = setmetatable({}, _base_0) - mt.__init(self, ...) - return self + __index = function(cls, name) + local val = rawget(_base_0, name) + if val == nil and _parent_0 then + return _parent_0[name] + else + return val + end + end, + __call = function(cls, ...) + local _self_0 = setmetatable({}, _base_0) + cls.__init(_self_0, ...) + return _self_0 end }) _base_0.__class = _class_0 return _class_0 -end)()
+end)()
+

A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed.

@@ -1160,12 +1574,16 @@ argument. The fat arrow handles the creation of a self argument.

Creating an instance of the class is done by calling the name of the class as a function.

- +
moonscriptlua
inv = Inventory!
+
+
+
+
moonscriptlua
inv = Inventory!
 inv\add_item "t-shirt"
-inv\add_item "pants"
-
local inv = Inventory()
+inv\add_item "pants"
local inv = Inventory()
 inv:add_item("t-shirt")
-inv:add_item("pants")
+inv:add_item("pants")
+

Because the instance of the class needs to be sent to the methods when they are called, the ‘' operator is used.

@@ -1176,7 +1594,9 @@ functions, but for other types of objects, undesired results may occur.

Consider the example below, the clothes property is shared amongst all instances, so modifications to it in one instance will show up in another:

- +
moonscriptlua
class Person
+
+
+
+
moonscriptlua
class Person
   clothes: {}
   give_item: (name) =>
     table.insert @clothes, name
@@ -1188,9 +1608,10 @@ instances, so modifications to it in one instance will show up in another:

b\give_item "shirt" -- will print both pants and shirt -print item for item in *a.clothes -
local Person
-Person = (function(_parent_0)
+print item for item in *a.clothes
local Person
+Person = (function()
+  local _parent_0 = nil
   local _base_0 = {
     clothes = { },
     give_item = function(self, name)
@@ -1199,20 +1620,30 @@ instances, so modifications to it in one instance will show up in another:

} _base_0.__index = _base_0 if _parent_0 then - setmetatable(_base_0, getmetatable(_parent_0).__index) + setmetatable(_base_0, _parent_0.__base) end local _class_0 = setmetatable({ __init = function(self, ...) if _parent_0 then return _parent_0.__init(self, ...) end - end + end, + __base = _base_0, + __name = "Person", + __parent = _parent_0 }, { - __index = _base_0, - __call = function(mt, ...) - local self = setmetatable({}, _base_0) - mt.__init(self, ...) - return self + __index = function(cls, name) + local val = rawget(_base_0, name) + if val == nil and _parent_0 then + return _parent_0[name] + else + return val + end + end, + __call = function(cls, ...) + local _self_0 = setmetatable({}, _base_0) + cls.__init(_self_0, ...) + return _self_0 end }) _base_0.__class = _class_0 @@ -1222,55 +1653,73 @@ instances, so modifications to it in one instance will show up in another:

local b = Person() a:give_item("pants") b:give_item("shirt") -do - local _item_0 = a.clothes - for _index_0 = 1, #_item_0 do - local item = _item_0[_index_0] - print(item) - end -end
+local _list_0 = a.clothes +for _index_0 = 1, #_list_0 do + local item = _list_0[_index_0] + print(item) +end
+

The proper way to avoid this problem is to create the mutable state of the object in the constructor:

- +
moonscriptlua
class Person
+
+
+
+
moonscriptlua
class Person
   new: =>
-    @clothes = {}
-
local Person
-Person = (function(_parent_0)
+    @clothes = {}
local Person
+Person = (function()
+  local _parent_0 = nil
   local _base_0 = { }
   _base_0.__index = _base_0
   if _parent_0 then
-    setmetatable(_base_0, getmetatable(_parent_0).__index)
+    setmetatable(_base_0, _parent_0.__base)
   end
   local _class_0 = setmetatable({
     __init = function(self)
       self.clothes = { }
-    end
+    end,
+    __base = _base_0,
+    __name = "Person",
+    __parent = _parent_0
   }, {
-    __index = _base_0,
-    __call = function(mt, ...)
-      local self = setmetatable({}, _base_0)
-      mt.__init(self, ...)
-      return self
+    __index = function(cls, name)
+      local val = rawget(_base_0, name)
+      if val == nil and _parent_0 then
+        return _parent_0[name]
+      else
+        return val
+      end
+    end,
+    __call = function(cls, ...)
+      local _self_0 = setmetatable({}, _base_0)
+      cls.__init(_self_0, ...)
+      return _self_0
     end
   })
   _base_0.__class = _class_0
   return _class_0
-end)()
+end)()
+

Inheritance

The extends keyword can be used in a class declaration to inherit the properties and methods from another class.

- +
moonscriptlua
class BackPack extends Inventory
+
+
+
+
moonscriptlua
class BackPack extends Inventory
   size: 10
   add_item: (name) =>
     if #@items > size then error "backpack is full"
-    super name
-
local BackPack
-BackPack = (function(_parent_0)
+    super name
local BackPack
+BackPack = (function()
+  local _parent_0 = Inventory
   local _base_0 = {
     size = 10,
     add_item = function(self, name)
@@ -1282,31 +1731,121 @@ properties and methods from another class.

} _base_0.__index = _base_0 if _parent_0 then - setmetatable(_base_0, getmetatable(_parent_0).__index) + setmetatable(_base_0, _parent_0.__base) end local _class_0 = setmetatable({ __init = function(self, ...) if _parent_0 then return _parent_0.__init(self, ...) end - end + end, + __base = _base_0, + __name = "BackPack", + __parent = _parent_0 }, { - __index = _base_0, - __call = function(mt, ...) - local self = setmetatable({}, _base_0) - mt.__init(self, ...) - return self + __index = function(cls, name) + local val = rawget(_base_0, name) + if val == nil and _parent_0 then + return _parent_0[name] + else + return val + end + end, + __call = function(cls, ...) + local _self_0 = setmetatable({}, _base_0) + cls.__init(_self_0, ...) + return _self_0 end }) _base_0.__class = _class_0 return _class_0 -end)(Inventory)
+end)()
-

Here we extend our Inventory class, and limit the amount of items it can carry. -The super keyword can be called as a function to call the function of the -same name in the super class. It can also be accessed like an object in order -to retrieve values in the parent class that might have been shadowed by the -child class.

+ +

Here we extend our Inventory class, and limit the amount of items it can carry.

+ +

Super

+ +

super is a special keyword that can be used in two different ways: It can be +treated as an object, or it can be called like a function. It only has special +functionality when inside a class.

+ +

When called as a function, it will call the function of the same name in the +parent class. The current self will automatically be passed as the first +argument. (As seen in the inheritance example above)

+ +

When super is used as a normal value, it is a reference to the parent class +object.

+ +

It can be accessed like any of object in order to retrieve values in the +parent class that might have been shadowed by the child class.

+ +

When the \ calling operator is used with super, self is inserted as the +first argument instead of the value of super itself. When using . to +retrieve a function, the raw function is returned.

+ +

A few examples of using super in different ways:

+ + + + + +
moonscriptlua
class MyClass extends ParentClass
+  a_method: =>
+    -- the following have the same effect:
+    super "hello", "world"
+    super\a_method "hello", "world"
+    super.a_method self, "hello", "world"
+
+    -- super as a value is equal to the parent class:
+    assert super == ParentClass
local MyClass
+MyClass = (function()
+  local _parent_0 = ParentClass
+  local _base_0 = {
+    a_method = function(self)
+      _parent_0.a_method(self, "hello", "world")
+      _parent_0.a_method(self, "hello", "world")
+      _parent_0.a_method(self, "hello", "world")
+      return assert(_parent_0 == ParentClass)
+    end
+  }
+  _base_0.__index = _base_0
+  if _parent_0 then
+    setmetatable(_base_0, _parent_0.__base)
+  end
+  local _class_0 = setmetatable({
+    __init = function(self, ...)
+      if _parent_0 then
+        return _parent_0.__init(self, ...)
+      end
+    end,
+    __base = _base_0,
+    __name = "MyClass",
+    __parent = _parent_0
+  }, {
+    __index = function(cls, name)
+      local val = rawget(_base_0, name)
+      if val == nil and _parent_0 then
+        return _parent_0[name]
+      else
+        return val
+      end
+    end,
+    __call = function(cls, ...)
+      local _self_0 = setmetatable({}, _base_0)
+      cls.__init(_self_0, ...)
+      return _self_0
+    end
+  })
+  _base_0.__class = _class_0
+  return _class_0
+end)()
+ + +

super can also be used on left side of a Function Stub. +The only major difference is that instead of the resulting function being bound +to the value of super, it is bound to self.

Types

@@ -1315,13 +1854,17 @@ special __class property. This property holds the class object. The object is what we call to build a new instance. We can also index the class object to retrieve class methods and properties.

- +
moonscriptlua
b = BackPack!
+
+
+
+
moonscriptlua
b = BackPack!
 assert b.__class == BackPack
 
-print BackPack.size -- prints 10
-
local b = BackPack()
+print BackPack.size -- prints 10
local b = BackPack()
 assert(b.__class == BackPack)
-print(BackPack.size)
+print(BackPack.size)
+

Export Statement

@@ -1331,15 +1874,21 @@ be declared as local, special syntax is required to declare a variable globally.

The export keyword makes it so any following assignments to the specified names will not be assigned locally.

-
moonscriptlua
export var_name, var_name2
-var_name, var_name3 = "hello", "world"
-
local var_name3
-var_name, var_name3 = "hello", "world"
+ + + + +
moonscriptlua
export var_name, var_name2
+var_name, var_name3 = "hello", "world"
local var_name3
+var_name, var_name3 = "hello", "world"
+

This is especially useful when declaring what will be externally visible in a module:

- +
moonscriptlua
-- my_module.moon
+
+
+
+
moonscriptlua
-- my_module.moon
 module "my_module", package.seeall
 export print_result
 
@@ -1353,8 +1902,8 @@ module:

my_module.print_result 4, 5 -- prints the result -print my_module.length 6, 7 -- errors, `length` not visible -
module("my_module", package.seeall)
+print my_module.length 6, 7 -- errors, `length` not visible
module("my_module", package.seeall)
 local length
 length = function(x, y)
   return math.sqrt(x * x + y * y)
@@ -1364,7 +1913,22 @@ module:

end require("my_module") my_module.print_result(4, 5) -print(my_module.length(6, 7))
+print(my_module.length(6, 7))
+ + +

Assignment can be combined with the export keyword to assign to global +variables directly:

+ + + + + +
moonscriptlua
export some_number, message_str = 100, "hello world"
some_number, message_str = 100, "hello world"
+ + +

Additionally, a class declaration can be prefixed with the export keyword in +order to export it.

Export All & Export Proper

@@ -1379,19 +1943,29 @@ capital letter.

Often you want to bring some values from a table into the current scope as local variables by their name. The import statement lets us accomplish this:

-
moonscriptlua
import insert from table
-
local insert = table.insert
+ + + + +
moonscriptlua
import insert from table
local insert = table.insert
+

The multiple names can be given, each separated by a comma:

-
moonscriptlua
import C, Ct, Cmt from lpeg
-
local C, Ct, Cmt = lpeg.C, lpeg.Ct, lpeg.Cmt
+ + + + +
moonscriptlua
import C, Ct, Cmt from lpeg
local C, Ct, Cmt = lpeg.C, lpeg.Ct, lpeg.Cmt
+

Sometimes a function requires that the table be sent in as the first argument (when using the \ syntax). As a shortcut, we can prefix the name with a \ to bind it to that table:

- +
moonscriptlua
-- some object
+
+
+
+
moonscriptlua
-- some object
 my_module =
     state: 100
     add: (value) =>
@@ -1399,15 +1973,23 @@ with a \ to bind it to that table:

import \add from my_module -print add(22) -- equivalent to calling my_module\get 22 -
local my_module = {
+print add(22) -- equivalent to calling my_module\get 22
local my_module = {
   state = 100,
   add = function(self, value)
     return self.state + value
   end
 }
-local add = moon.bind(my_module.add, my_module)
-print(add(22))
+local add = (function() + local _base_0 = my_module + local _fn_0 = _base_0.add + return function(...) + return _fn_0(_base_0, ...) + end +end)() +print(add(22))
+

With Statement

@@ -1425,50 +2007,58 @@ those operations applied to the object we are using with on.

For example, we work with a newly created object:

- +
moonscriptlua
with Person!
+
+
+
+
moonscriptlua
with Person!
   .name = "Oswald"
   \add_relative my_dad
   \save!
-  print .name
-
do
+  print .name
do
   local _with_0 = Person()
   _with_0.name = "Oswald"
   _with_0:add_relative(my_dad)
   _with_0:save()
   print(_with_0.name)
-end
+end
+

The with statement can also be used as an expression which returns the value it has been giving access to.

- +
moonscriptlua
file = with File "favorite_foods.txt"
-  \set_encoding "utf8"
-
local file
+
+
+
+
moonscriptlua
file = with File "favorite_foods.txt"
+  \set_encoding "utf8"
local file
 do
   local _with_0 = File("favorite_foods.txt")
   _with_0:set_encoding("utf8")
   file = _with_0
-end
+end
+

Or…

- +
moonscriptlua
create_person = (name,  relatives) ->
+
+
+
+
moonscriptlua
create_person = (name,  relatives) ->
   with Person!
     .name = name
     \add_relative relative for relative in *relatives
 
-me = create_person "Leaf", {dad, mother, sister}
-
local create_person
+me = create_person "Leaf", {dad, mother, sister}
local create_person
 create_person = function(name, relatives)
   do
     local _with_0 = Person()
     _with_0.name = name
-    do
-      local _item_0 = relatives
-      for _index_0 = 1, #_item_0 do
-        local relative = _item_0[_index_0]
-        _with_0:add_relative(relative)
-      end
+    local _list_0 = relatives
+    for _index_0 = 1, #_list_0 do
+      local relative = _list_0[_index_0]
+      _with_0:add_relative(relative)
     end
     return _with_0
   end
@@ -1477,7 +2067,9 @@ it has been giving access to.

dad, mother, sister -})
+})
+

Function Stubs

@@ -1493,7 +2085,9 @@ function in the correct context of the object.

Its syntax is the same as calling an instance method with the \ operator but with no argument list provided.

- +
moonscriptlua
my_object = {
+
+
+
+
moonscriptlua
my_object = {
   value: 1000
   write: => print "the value:", @value
 }
@@ -1508,8 +2102,8 @@ with no argument list provided.

-- function stub syntax -- lets us bundle the object into a new function -run_callback my_object\write -
local my_object = {
+run_callback my_object\write
local my_object = {
   value = 1000,
   write = function(self)
     return print("the value:", self.value)
@@ -1526,7 +2120,9 @@ with no argument list provided.

return function(...) return _fn_0(_base_0, ...) end -end)())
+end)())
+

The Using Clause; Controlling Destructive Assignment

@@ -1534,7 +2130,9 @@ with no argument list provided.

code we write, things can get unwieldy as the code size increases. Consider the following snippet:

- +
moonscriptlua
i = 100
+
+
+
+
moonscriptlua
i = 100
 
 -- many lines of code...
 
@@ -1546,8 +2144,8 @@ the following snippet:

my_func() -print i -- will print 0 -
local i = 100
+print i -- will print 0
local i = 100
 local my_func
 my_func = function()
   i = 10
@@ -1557,7 +2155,9 @@ the following snippet:

end end my_func() -print(i)
+print(i)
+

In my_func, we've overwritten the value of i mistakenly. In this example it is quite obvious, but consider a large, or foreign code base where it isn’t @@ -1570,25 +2170,31 @@ on change, in order to prevent us from changing others by accident.

variables are overwritten in assignment. The using clause is placed after the argument list in a function, or in place of it if there are no arguments.

- +
moonscriptlua
i = 100
+
+
+
+
moonscriptlua
i = 100
 
 my_func = (using nil) ->
     i = "hello" -- a new local variable is created here
 
 my_func()
-print i -- prints 100, i is unaffected
-
local i = 100
+print i -- prints 100, i is unaffected
local i = 100
 local my_func
 my_func = function()
   local i = "hello"
 end
 my_func()
-print(i)
+print(i)
+

Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified:

- +
moonscriptlua
tmp = 1213
+
+
+
+
moonscriptlua
tmp = 1213
 i, k = 100, 50
 
 my_func = (add using k,i) ->
@@ -1597,8 +2203,8 @@ accessed, they just cant be modified:

k += tmp my_func(22) -print i,k -- these have been updated -
local tmp = 1213
+print i,k -- these have been updated
local tmp = 1213
 local i, k = 100, 50
 local my_func
 my_func = function(add)
@@ -1608,7 +2214,9 @@ accessed, they just cant be modified:

return k end my_func(22) -print(i, k)
+print(i, k)
+

MoonScript API

@@ -1617,8 +2225,12 @@ accessed, they just cant be modified:

Upon installing MoonScript, a moonscript module is made available. The best use of this module is making your Lua’s require function MoonScript aware.

-
moonscriptlua
require "moonscript"
-
require("moonscript")
+ + + + +
moonscriptlua
require "moonscript"
require("moonscript")
+

After moonscript is required, Lua’s package loader is updated to search for .moon files on any subsequent calls to require. The search path for .moon @@ -1648,17 +2260,21 @@ can make debugging particularly difficult.

Consider the following file with a bug:

- +
moonscriptlua
add_numbers = (x,y) -> x + z
-print add_numbers 10,0
-
local add_numbers
+
+
+
+
moonscriptlua
add_numbers = (x,y) -> x + z
+print add_numbers 10,0
local add_numbers
 add_numbers = function(x, y)
   return x + z
 end
-print(add_numbers(10, 0))
+print(add_numbers(10, 0))
+

The following error is generated:

-
moon:err.moon:1: attempt to perform arithmetic on global 'z' (a nil value)
+
moon:err.moon:1: attempt to perform arithmetic on global 'z' (a nil value)
 stack traceback:
     err.moon:1: in function 'add_numbers'
     err.moon:2: in main chunk
@@ -1679,7 +2295,9 @@ Lua code from MoonScript code.

Here is a quick example of how you would compile a MoonScript string to a Lua String:

- +
moonscriptlua
require "moonscript.parse"
+
+
+
+
moonscriptlua
require "moonscript.parse"
 require "moonscript.compile"
 
 import parse, compile from moonscript
@@ -1695,8 +2313,8 @@ String:

error compile.format_error err, pos, moon_code -- our code is ready -print lua_code -
require("moonscript.parse")
+print lua_code
require("moonscript.parse")
 require("moonscript.compile")
 local parse, compile = moonscript.parse, moonscript.compile
 local moon_code = [[(-> print "hello world")!]]
@@ -1709,7 +2327,9 @@ String:

if not lua_code then error(compile.format_error(err, pos, moon_code)) end -print(lua_code)
+print(lua_code)
+

Command Line Use

@@ -1724,8 +2344,9 @@ String:

without needing a separate compile step. All MoonsScript files are compiled in memory as they are run.

-
~> moon my_script.moon
-
+
$ moon my_script.moon
+
+

Any MoonScript files that are required will also be compiled and run automatically.

@@ -1743,8 +2364,9 @@ flag.

It takes a list of files, compiles them all, and creates the associated .lua files in the same directories.

-
~> moonc my_script1.moon my_script2.moon ...
-
+
$ moonc my_script1.moon my_script2.moon ...
+
+

You can control where the compiled files are put using the -t flag, followed by a directory.

@@ -1762,29 +2384,30 @@ required.

License (MIT)

-

Copyright © 2011 by Leaf Corcoran

+
Copyright (C) 2011 by Leaf Corcoran
 
-

Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the “Software”), to deal +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions:

+furnished to do so, subject to the following conditions: -

The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software.

+The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE.

+THE SOFTWARE. +
- + diff --git a/docs/standard_lib.html b/docs/standard_lib.html new file mode 100644 index 0000000..4c64f01 --- /dev/null +++ b/docs/standard_lib.html @@ -0,0 +1,476 @@ + + + + + + MoonScript v0.2.0 - Standard Library + + + + +
+

MoonScript v0.2.0 - Standard Library

+
+ + + +
+

The MoonScript installation comes with a small kernel of functions that can be +used to perform various common things.

+ +

The entire library is currently contained in a single object. We can bring this +moon object into scope by requiring "moon".

+ +
require "moon"
+-- `moon.p` is the debug printer
+moon.p { hello: "world" }
+
+ + +

If you prefer to just inject all of the functions into the current scope, you +can require "moon.all" instead. The following has the same effect as above:

+ +
require "moon.all"
+p { hello: "world" }
+
+ + +

All of the functions are compatible with Lua in addition to MoonScript, but +some of them only make sense in the context of MoonScript.

+ +

MoonScript Standard Library

+ +

This is an overview of all the included functions. +All of the examples assume that the standard library has been included with +require "moon.all".

+ +

Printing Functions

+ +

p(arg)

+ +

Prints a formatted version of an object. Excellent for inspecting the contents +of a table.

+ +

Table Functions

+ +

run_with_scope(fn, scope, [args...])

+ +

Mutates the environment of function fn and runs the function with any extra +arguments in args.... Returns the result of the function.

+ +

The environment of the function is set to a new table whose metatable will use +scope to look up values. scope must be a table. If scope does not have an +entry for a value, it will fall back on the original environment.

+ +
my_env = {
+  secret_function: -> print "shhh this is secret"
+  say_hi: -> print "hi there!"
+}
+
+say_hi = -> print "I am a closure"
+
+fn = ->
+  secret_function!
+  say_hi!
+
+run_with_scope fn, my_env
+
+ + +

Note that any closure values will always take precedence against global name +lookups in the environment. In the example above, the say_hi in the +environment has been shadowed by the local variable say_hi.

+ +

defaultbl([tbl,] fn)

+ +

Sets the __index of table tbl to use the function fn to generate table +values when a missing key is looked up.

+ +

extend(arg1, arg2, [rest...])

+ +

Chains together a series of tables by their metatable’s __index property. +Overwrites the metatable of all objects exept for the last with a new table +whose __index is set to the next table.

+ +

Returns the first argument.

+ +
a = { hello: "world" }
+b = { okay: "sure" }
+
+extend a, b
+
+print a.okay
+
+ + +

copy(tbl)

+ +

Creates a shallow copy of a table, equivalent to:

+ +
copy = (arg) -> {k,v for k,v in pairs self}
+
+ + +

Class/Object Functions

+ +

is_object(value)

+ +

Returns true if value is an instance of a MoonScript class, false otherwise.

+ +

type(value)

+ +

If value is an instance of a MoonScript class, then return it’s class object. +Otherwise, return the result of calling Lua’s type method.

+ +
class MyClass
+  nil
+
+x = MyClass!
+assert type(x) == MyClass
+
+ + +

bind_methods(obj)

+ +

Takes an instance of an object, returns a proxy to the object whose methods can +be called without providing self as the first argument.

+ +
obj = SomeClass!
+
+bound_obj = bind_methods obj
+
+-- following have the same effect
+obj\hello!
+bound_obj.hello!
+
+ + +

It lazily creates and stores in the proxy table the bound methods when they +are first called.

+ +

mixin(obj, class, [args...])

+ +

Copies the methods of a class cls into the table obj, then calls the +constructor of the class with the obj as the receiver.

+ +

In this example we add the functionality of First to an instance of Second +without ever instancing First.

+ +
class First
+  new: (@var) =>
+  show_var: => print "var is:", @var
+
+class Second
+  new: =>
+    mixin self, First, "hi"
+
+a = Second!
+a\show_var!
+
+ + +

Be weary of name collisions when mixing in other classes, names will be +overwritten.

+ +

mixin_object(obj, other_obj, method_names)

+ +

Inserts into obj methods from other_obj whose names are listen in +method_names. The inserted methods are bound methods that will run with +other_obj as the receiver.

+ +
class List 
+  add: (item) => print "adding to", self
+  remove: (item) => print "removing from", self
+
+class Encapsulation
+  new: =>
+    @list = List!
+    mixin_object self, @list, {"add", "remove"}
+
+e = Encapsulation!
+e.add "something"
+
+ + +

mixin_table(a, b, [names])

+ +

Copies the elements of table b into table a. If names is provided, then +only those names are copied.

+ +

Misc Functions

+ +

fold(items, fn)

+ +

Calls function fn repeatedly with the accumulated value and the current value +by iterating over items. The accumulated value is the result of the last call +to fn, or, in the base case, the first value. The current value is the value +being iterated over starting with the second item.

+ +

items is a normal array table.

+ +

For example, to sum all numbers in a list:

+ +
numbers = {4,3,5,6,7,2,3}
+sum = fold numbers, (a,b) -> a + b
+
+ + +

Debug Functions

+ +

debug.upvalue(fn, key[, value])

+ +

Gets or sets the value of an upvalue for a function by name.

+ +
+ + + + + + + +