summaryrefslogtreecommitdiff
path: root/doc/yue-en.md
diff options
context:
space:
mode:
Diffstat (limited to 'doc/yue-en.md')
-rw-r--r--doc/yue-en.md2497
1 files changed, 2 insertions, 2495 deletions
diff --git a/doc/yue-en.md b/doc/yue-en.md
index 3f8546a..764bc1a 100644
--- a/doc/yue-en.md
+++ b/doc/yue-en.md
@@ -1,11 +1,5 @@
1---
2title: Reference
3---
4
5# YueScript Documentation 1# YueScript Documentation
6 2
7<img src="/image/yuescript.svg" width="250px" height="250px" alt="logo" style="padding-top: 3em; padding-bottom: 2em;"/>
8
9Welcome to the <b>YueScript</b> official documentation!<br/> 3Welcome to the <b>YueScript</b> official documentation!<br/>
10Here you can find the language features, usage, reference examples and resources.<br/> 4Here you can find the language features, usage, reference examples and resources.<br/>
11Please select a chapter from the sidebar to start learning about YueScript. 5Please select a chapter from the sidebar to start learning about YueScript.
@@ -21,17 +15,6 @@ do
21print var -- nil here 15print var -- nil here
22``` 16```
23 17
24<YueDisplay>
25
26```yue
27do
28 var = "hello"
29 print var
30print var -- nil here
31```
32
33</YueDisplay>
34
35YueScript's **do** can also be used an expression . Allowing you to combine multiple lines into one. The result of the do expression is the last statement in its body. 18YueScript's **do** can also be used an expression . Allowing you to combine multiple lines into one. The result of the do expression is the last statement in its body.
36 19
37`do` expressions also support using `break` to interrupt control flow and return multiple values early: 20`do` expressions also support using `break` to interrupt control flow and return multiple values early:
@@ -44,18 +27,6 @@ status, value = do
44 break "small", n 27 break "small", n
45``` 28```
46 29
47<YueDisplay>
48
49```yue
50status, value = do
51 n = 12
52 if n > 10
53 break "large", n
54 break "small", n
55```
56
57</YueDisplay>
58
59```yuescript 30```yuescript
60counter = do 31counter = do
61 i = 0 32 i = 0
@@ -67,21 +38,6 @@ print counter!
67print counter! 38print counter!
68``` 39```
69 40
70<YueDisplay>
71
72```yue
73counter = do
74 i = 0
75 ->
76 i += 1
77 i
78
79print counter!
80print counter!
81```
82
83</YueDisplay>
84
85```yuescript 41```yuescript
86tbl = { 42tbl = {
87 key: do 43 key: do
@@ -90,18 +46,6 @@ tbl = {
90} 46}
91``` 47```
92 48
93<YueDisplay>
94
95```yue
96tbl = {
97 key: do
98 print "assigning key!"
99 1234
100}
101```
102
103</YueDisplay>
104
105# Line Decorators 49# Line Decorators
106 50
107For convenience, the for loop and if statement can be applied to single statements at the end of the line: 51For convenience, the for loop and if statement can be applied to single statements at the end of the line:
@@ -110,28 +54,12 @@ For convenience, the for loop and if statement can be applied to single statemen
110print "hello world" if name == "Rob" 54print "hello world" if name == "Rob"
111``` 55```
112 56
113<YueDisplay>
114
115```yue
116print "hello world" if name == "Rob"
117```
118
119</YueDisplay>
120
121And with basic loops: 57And with basic loops:
122 58
123```yuescript 59```yuescript
124print "item: ", item for item in *items 60print "item: ", item for item in *items
125``` 61```
126 62
127<YueDisplay>
128
129```yue
130print "item: ", item for item in *items
131```
132
133</YueDisplay>
134
135And with while loops: 63And with while loops:
136 64
137```yuescript 65```yuescript
@@ -140,16 +68,6 @@ game\update! while game\isRunning!
140reader\parse_line! until reader\eof! 68reader\parse_line! until reader\eof!
141``` 69```
142 70
143<YueDisplay>
144
145```yue
146game\update! while game\isRunning!
147
148reader\parse_line! until reader\eof!
149```
150
151</YueDisplay>
152
153# Macro 71# Macro
154 72
155## Common Usage 73## Common Usage
@@ -185,39 +103,6 @@ if $and f1!, f2!, f3!
185 print "OK" 103 print "OK"
186``` 104```
187 105
188<YueDisplay>
189
190```yue
191macro PI2 = -> math.pi * 2
192area = $PI2 * 5
193
194macro HELLO = -> "'hello world'"
195print $HELLO
196
197macro config = (debugging) ->
198 global debugMode = debugging == "true"
199 ""
200
201macro asserts = (cond) ->
202 debugMode and "assert #{cond}" or ""
203
204macro assert = (cond) ->
205 debugMode and "assert #{cond}" or "#{cond}"
206
207$config true
208$asserts item ~= nil
209
210$config false
211value = $assert item
212
213-- the passed expressions are treated as strings
214macro and = (...) -> "#{ table.concat {...}, ' and ' }"
215if $and f1!, f2!, f3!
216 print "OK"
217```
218
219</YueDisplay>
220
221## Insert Raw Codes 106## Insert Raw Codes
222 107
223A macro function can either return a YueScript string or a config table containing Lua codes. 108A macro function can either return a YueScript string or a config table containing Lua codes.
@@ -248,36 +133,6 @@ end
248]==] 133]==]
249``` 134```
250 135
251<YueDisplay>
252
253```yue
254macro yueFunc = (var) -> "local #{var} = ->"
255$yueFunc funcA
256funcA = -> "fail to assign to the Yue macro defined variable"
257
258macro luaFunc = (var) -> {
259 code: "local function #{var}() end"
260 type: "lua"
261}
262$luaFunc funcB
263funcB = -> "fail to assign to the Lua macro defined variable"
264
265macro lua = (code) -> {
266 :code
267 type: "lua"
268}
269
270-- the raw string leading and ending symbols are auto trimed
271$lua[==[
272-- raw Lua codes insertion
273if cond then
274 print("output")
275end
276]==]
277```
278
279</YueDisplay>
280
281## Export Macro 136## Export Macro
282 137
283Macro functions can be exported from a module and get imported in another module. You have to put export macro functions in a single file to be used, and only macro definition, macro importing and macro expansion in place can be put into the macro exporting module. 138Macro functions can be exported from a module and get imported in another module. You have to put export macro functions in a single file to be used, and only macro definition, macro importing and macro expansion in place can be put into the macro exporting module.
@@ -297,28 +152,6 @@ import "utils" as {
297[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ 152[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _
298``` 153```
299 154
300<YueDisplay>
301
302```yue
303-- file: utils.yue
304export macro map = (items, action) -> "[#{action} for _ in *#{items}]"
305export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]"
306export macro foreach = (items, action) -> "for _ in *#{items}
307 #{action}"
308
309-- file main.yue
310-- import function is not available in browser, try it in a real environment
311--[[
312import "utils" as {
313 $, -- symbol to import all macros
314 $foreach: $each -- rename macro $foreach to $each
315}
316[1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _
317]]
318```
319
320</YueDisplay>
321
322## Builtin Macro 155## Builtin Macro
323 156
324There are some builtin macros but you can override them by declaring macros with the same names. 157There are some builtin macros but you can override them by declaring macros with the same names.
@@ -328,15 +161,6 @@ print $FILE -- get string of current module name
328print $LINE -- get number 2 161print $LINE -- get number 2
329``` 162```
330 163
331<YueDisplay>
332
333```yue
334print $FILE -- get string of current module name
335print $LINE -- get number 2
336```
337
338</YueDisplay>
339
340## Generating Macros with Macros 164## Generating Macros with Macros
341 165
342In YueScript, macro functions allow you to generate code at compile time. By nesting macro functions, you can create more complex generation patterns. This feature enables you to define a macro function that generates another macro function, allowing for more dynamic code generation. 166In YueScript, macro functions allow you to generate code at compile time. By nesting macro functions, you can create more complex generation patterns. This feature enables you to define a macro function that generates another macro function, allowing for more dynamic code generation.
@@ -359,28 +183,6 @@ print "Valid enum type:", $BodyType Static
359-- print "Compilation error with enum type:", $BodyType Unknown 183-- print "Compilation error with enum type:", $BodyType Unknown
360``` 184```
361 185
362<YueDisplay>
363
364```yue
365macro Enum = (...) ->
366 items = {...}
367 itemSet = {item, true for item in *items}
368 (item) ->
369 error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item]
370 "\"#{item}\""
371
372macro BodyType = $Enum(
373 Static
374 Dynamic
375 Kinematic
376)
377
378print "Valid enum type:", $BodyType Static
379-- print "Compilation error with enum type:", $BodyType Unknown
380```
381
382</YueDisplay>
383
384## Argument Validation 186## Argument Validation
385 187
386You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time. 188You can declare the expected AST node types in the argument list, and check whether the incoming macro arguments meet the expectations at compile time.
@@ -395,20 +197,6 @@ macro printNumAndStr = (num `Num, str `String) -> |
395$printNumAndStr 123, "hello" 197$printNumAndStr 123, "hello"
396``` 198```
397 199
398<YueDisplay>
399
400```yue
401macro printNumAndStr = (num `Num, str `String) -> |
402 print(
403 #{num}
404 #{str}
405 )
406
407$printNumAndStr 123, "hello"
408```
409
410</YueDisplay>
411
412If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place. 200If you need more flexible argument checking, you can use the built-in `$is_ast` macro function to manually check at the appropriate place.
413 201
414```yuescript 202```yuescript
@@ -420,19 +208,6 @@ macro printNumAndStr = (num, str) ->
420$printNumAndStr 123, "hello" 208$printNumAndStr 123, "hello"
421``` 209```
422 210
423<YueDisplay>
424
425```yue
426macro printNumAndStr = (num, str) ->
427 error "expected Num as first argument" unless $is_ast Num, num
428 error "expected String as second argument" unless $is_ast String, str
429 "print(#{num}, #{str})"
430
431$printNumAndStr 123, "hello"
432```
433
434</YueDisplay>
435
436For more details about available AST nodes, please refer to the uppercased definitions in [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp). 211For more details about available AST nodes, please refer to the uppercased definitions in [yue_parser.cpp](https://github.com/IppClub/YueScript/blob/main/src/yuescript/yue_parser.cpp).
437 212
438# Try 213# Try
@@ -467,38 +242,6 @@ catch err
467 print result 242 print result
468``` 243```
469 244
470<YueDisplay>
471
472```yue
473try
474 func 1, 2, 3
475catch err
476 print yue.traceback err
477
478success, result = try
479 func 1, 2, 3
480catch err
481 yue.traceback err
482
483try func 1, 2, 3
484catch err
485 print yue.traceback err
486
487success, result = try func 1, 2, 3
488
489try
490 print "trying"
491 func 1, 2, 3
492
493-- working with if assignment pattern
494if success, result := try func 1, 2, 3
495catch err
496 print yue.traceback err
497 print result
498```
499
500</YueDisplay>
501
502## Try? 245## Try?
503 246
504`try?` is a simplified use for error handling syntax that omit the boolean status from the `try` statement, and it will return the result from the try block when success, return nil instead of error object otherwise. 247`try?` is a simplified use for error handling syntax that omit the boolean status from the `try` statement, and it will return the result from the try block when success, return nil instead of error object otherwise.
@@ -521,44 +264,14 @@ catch e
521 e 264 e
522``` 265```
523 266
524<YueDisplay>
525
526```yue
527a, b, c = try? func!
528
529-- with nil coalescing operator
530a = (try? func!) ?? "default"
531
532-- as function argument
533f try? func!
534
535-- with catch block
536f try?
537 print 123
538 func!
539catch e
540 print e
541 e
542```
543
544</YueDisplay>
545
546# Table Literals 267# Table Literals
547 268
548Like in Lua, tables are delimited in curly braces. 269Like in Lua, tables are delimited in curly braces.
549 270
550```yuescript 271```yuescript
551some_values = [1, 2, 3, 4] 272some_values = {1, 2, 3, 4}
552```
553
554<YueDisplay>
555
556```yue
557some_values = [1, 2, 3, 4]
558``` 273```
559 274
560</YueDisplay>
561
562Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**). 275Unlike Lua, assigning a value to a key in a table is done with **:** (instead of **=**).
563 276
564```yuescript 277```yuescript
@@ -569,18 +282,6 @@ some_values = {
569} 282}
570``` 283```
571 284
572<YueDisplay>
573
574```yue
575some_values = {
576 name: "Bill",
577 age: 200,
578 ["favorite food"]: "rice"
579}
580```
581
582</YueDisplay>
583
584The curly braces can be left off if a single table of key value pairs is being assigned. 285The curly braces can be left off if a single table of key value pairs is being assigned.
585 286
586```yuescript 287```yuescript
@@ -590,17 +291,6 @@ profile =
590 favorite_foods: ["ice cream", "donuts"] 291 favorite_foods: ["ice cream", "donuts"]
591``` 292```
592 293
593<YueDisplay>
594
595```yue
596profile =
597 height: "4 feet",
598 shoe_size: 13,
599 favorite_foods: ["ice cream", "donuts"]
600```
601
602</YueDisplay>
603
604Newlines can be used to delimit values instead of a comma (or both): 294Newlines can be used to delimit values instead of a comma (or both):
605 295
606```yuescript 296```yuescript
@@ -612,19 +302,6 @@ values = {
612} 302}
613``` 303```
614 304
615<YueDisplay>
616
617```yue
618values = {
619 1, 2, 3, 4
620 5, 6, 7, 8
621 name: "superman"
622 occupation: "crime fighting"
623}
624```
625
626</YueDisplay>
627
628When creating a single line table literal, the curly braces can also be left off: 305When creating a single line table literal, the curly braces can also be left off:
629 306
630```yuescript 307```yuescript
@@ -633,16 +310,6 @@ my_function dance: "Tango", partner: "none"
633y = type: "dog", legs: 4, tails: 1 310y = type: "dog", legs: 4, tails: 1
634``` 311```
635 312
636<YueDisplay>
637
638```yue
639my_function dance: "Tango", partner: "none"
640
641y = type: "dog", legs: 4, tails: 1
642```
643
644</YueDisplay>
645
646The keys of a table literal can be language keywords without being escaped: 313The keys of a table literal can be language keywords without being escaped:
647 314
648```yuescript 315```yuescript
@@ -652,17 +319,6 @@ tbl = {
652} 319}
653``` 320```
654 321
655<YueDisplay>
656
657```yue
658tbl = {
659 do: "something"
660 end: "hunger"
661}
662```
663
664</YueDisplay>
665
666If 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: 322If 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:
667 323
668```yuescript 324```yuescript
@@ -673,18 +329,6 @@ person = { :hair, :height, shoe_size: 40 }
673print_table :hair, :height 329print_table :hair, :height
674``` 330```
675 331
676<YueDisplay>
677
678```yue
679hair = "golden"
680height = 200
681person = { :hair, :height, shoe_size: 40 }
682
683print_table :hair, :height
684```
685
686</YueDisplay>
687
688If you want the key of a field in the table to to be result of an expression, then you can wrap it in **[ ]**, just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters. 332If you want the key of a field in the table to to be result of an expression, then you can wrap it in **[ ]**, just like in Lua. You can also use a string literal directly as a key, leaving out the square brackets. This is useful if your key has any special characters.
689 333
690```yuescript 334```yuescript
@@ -694,33 +338,13 @@ t = {
694} 338}
695``` 339```
696 340
697<YueDisplay> 341Lua tables have both an array part and a hash part, but sometimes it's useful to make a semantic distinction between the two. You can use **[ ]** instead of **{ }** to explicitly declare a table as an array, doing so will prevent any key-value pairs from being written inside it.
698
699```yue
700t = {
701 [1 + 2]: "hello"
702 "hello world": true
703}
704```
705
706</YueDisplay>
707
708Lua tables have both an array part and a hash part, but sometimes you want to make a semantic distinction between array and hash usage when writing Lua tables. Then you can write Lua table with **[ ]** instead of **{ }** to represent an array table and writing any key value pair in a list table won't be allowed.
709 342
710```yuescript 343```yuescript
711some_values = [1, 2, 3, 4] 344some_values = [1, 2, 3, 4]
712list_with_one_element = [1, ] 345list_with_one_element = [1, ]
713``` 346```
714 347
715<YueDisplay>
716
717```yue
718some_values = [1, 2, 3, 4]
719list_with_one_element = [1, ]
720```
721
722</YueDisplay>
723
724# Comprehensions 348# Comprehensions
725 349
726Comprehensions 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. 350Comprehensions 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.
@@ -734,43 +358,18 @@ items = [ 1, 2, 3, 4 ]
734doubled = [item * 2 for i, item in ipairs items] 358doubled = [item * 2 for i, item in ipairs items]
735``` 359```
736 360
737<YueDisplay>
738
739```yue
740items = [ 1, 2, 3, 4 ]
741doubled = [item * 2 for i, item in ipairs items]
742```
743
744</YueDisplay>
745
746The items included in the new table can be restricted with a when clause: 361The items included in the new table can be restricted with a when clause:
747 362
748```yuescript 363```yuescript
749slice = [item for i, item in ipairs items when i > 1 and i < 3] 364slice = [item for i, item in ipairs items when i > 1 and i < 3]
750``` 365```
751 366
752<YueDisplay>
753
754```yue
755slice = [item for i, item in ipairs items when i > 1 and i < 3]
756```
757
758</YueDisplay>
759
760Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as: 367Because it is common to iterate over the values of a numerically indexed table, an **\*** operator is introduced. The doubled example can be rewritten as:
761 368
762```yuescript 369```yuescript
763doubled = [item * 2 for item in *items] 370doubled = [item * 2 for item in *items]
764``` 371```
765 372
766<YueDisplay>
767
768```yue
769doubled = [item * 2 for item in *items]
770```
771
772</YueDisplay>
773
774In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect: 373In list comprehensions, you can also use the spread operator `...` to flatten nested lists, achieving a flat map effect:
775 374
776```yuescript 375```yuescript
@@ -782,19 +381,6 @@ flat = [...v for k,v in pairs data]
782-- flat is now [1, 2, 3, 4, 5, 6] 381-- flat is now [1, 2, 3, 4, 5, 6]
783``` 382```
784 383
785<YueDisplay>
786
787```yue
788data =
789 a: [1, 2, 3]
790 b: [4, 5, 6]
791
792flat = [...v for k,v in pairs data]
793-- flat is now [1, 2, 3, 4, 5, 6]
794```
795
796</YueDisplay>
797
798The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause. 384The for and when clauses can be chained as much as desired. The only requirement is that a comprehension has at least one for clause.
799 385
800Using multiple for clauses is the same as using nested loops: 386Using multiple for clauses is the same as using nested loops:
@@ -807,32 +393,12 @@ points = [ [x, y] for x in *x_coords \
807for y in *y_coords] 393for y in *y_coords]
808``` 394```
809 395
810<YueDisplay>
811
812```yue
813x_coords = [4, 5, 6, 7]
814y_coords = [9, 2, 3]
815
816points = [ [x, y] for x in *x_coords \
817for y in *y_coords]
818```
819
820</YueDisplay>
821
822Numeric for loops can also be used in comprehensions: 396Numeric for loops can also be used in comprehensions:
823 397
824```yuescript 398```yuescript
825evens = [i for i = 1, 100 when i % 2 == 0] 399evens = [i for i = 1, 100 when i % 2 == 0]
826``` 400```
827 401
828<YueDisplay>
829
830```yue
831evens = [i for i = 1, 100 when i % 2 == 0]
832```
833
834</YueDisplay>
835
836## Table Comprehensions 402## Table Comprehensions
837 403
838The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration. 404The syntax for table comprehensions is very similar, only differing by using **{** and **}** and taking two values from each iteration.
@@ -849,32 +415,10 @@ thing = {
849thing_copy = {k, v for k, v in pairs thing} 415thing_copy = {k, v for k, v in pairs thing}
850``` 416```
851 417
852<YueDisplay>
853
854```yue
855thing = {
856 color: "red"
857 name: "fast"
858 width: 123
859}
860
861thing_copy = {k, v for k, v in pairs thing}
862```
863
864</YueDisplay>
865
866```yuescript 418```yuescript
867no_color = {k, v for k, v in pairs thing when k != "color"} 419no_color = {k, v for k, v in pairs thing when k != "color"}
868``` 420```
869 421
870<YueDisplay>
871
872```yue
873no_color = {k, v for k, v in pairs thing when k != "color"}
874```
875
876</YueDisplay>
877
878The **\*** operator is also supported. Here we create a square root look up table for a few numbers. 422The **\*** operator is also supported. Here we create a square root look up table for a few numbers.
879 423
880```yuescript 424```yuescript
@@ -882,15 +426,6 @@ numbers = [1, 2, 3, 4]
882sqrts = {i, math.sqrt i for i in *numbers} 426sqrts = {i, math.sqrt i for i in *numbers}
883``` 427```
884 428
885<YueDisplay>
886
887```yue
888numbers = [1, 2, 3, 4]
889sqrts = {i, math.sqrt i for i in *numbers}
890```
891
892</YueDisplay>
893
894The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value: 429The key-value tuple in a table comprehension can also come from a single expression, in which case the expression should return two values. The first is used as the key and the second is used as the value:
895 430
896In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value. 431In this example we convert an array of pairs to a table where the first item in the pair is the key and the second is the value.
@@ -900,15 +435,6 @@ tuples = [ ["hello", "world"], ["foo", "bar"]]
900tbl = {unpack tuple for tuple in *tuples} 435tbl = {unpack tuple for tuple in *tuples}
901``` 436```
902 437
903<YueDisplay>
904
905```yue
906tuples = [ ["hello", "world"], ["foo", "bar"]]
907tbl = {unpack tuple for tuple in *tuples}
908```
909
910</YueDisplay>
911
912## Slicing 438## Slicing
913 439
914A special syntax is provided to restrict the items that are iterated over when using the **\*** operator. This is equivalent to setting the iteration bounds and a step size in a for loop. 440A special syntax is provided to restrict the items that are iterated over when using the **\*** operator. This is equivalent to setting the iteration bounds and a step size in a for loop.
@@ -919,42 +445,18 @@ Here we can set the minimum and maximum bounds, taking all items with indexes be
919slice = [item for item in *items[1, 5]] 445slice = [item for item in *items[1, 5]]
920``` 446```
921 447
922<YueDisplay>
923
924```yue
925slice = [item for item in *items[1, 5]]
926```
927
928</YueDisplay>
929
930Any 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: 448Any 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:
931 449
932```yuescript 450```yuescript
933slice = [item for item in *items[2,]] 451slice = [item for item in *items[2,]]
934``` 452```
935 453
936<YueDisplay>
937
938```yue
939slice = [item for item in *items[2,]]
940```
941
942</YueDisplay>
943
944If 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, …) 454If 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, …)
945 455
946```yuescript 456```yuescript
947slice = [item for item in *items[,,2]] 457slice = [item for item in *items[,,2]]
948``` 458```
949 459
950<YueDisplay>
951
952```yue
953slice = [item for item in *items[,,2]]
954```
955
956</YueDisplay>
957
958Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table. 460Both the minimum and maximum bounds can be negative, which means that the bounds are counted from the end of the table.
959 461
960```yuescript 462```yuescript
@@ -962,29 +464,12 @@ Both the minimum and maximum bounds can be negative, which means that the bounds
962slice = [item for item in *items[-4,-1]] 464slice = [item for item in *items[-4,-1]]
963``` 465```
964 466
965<YueDisplay>
966
967```yue
968-- take the last 4 items
969slice = [item for item in *items[-4,-1]]
970```
971
972</YueDisplay>
973
974The step size can also be negative, which means that the items are taken in reverse order. 467The step size can also be negative, which means that the items are taken in reverse order.
975 468
976```yuescript 469```yuescript
977reverse_slice = [item for item in *items[-1,1,-1]] 470reverse_slice = [item for item in *items[-1,1,-1]]
978``` 471```
979 472
980<YueDisplay>
981
982```yue
983reverse_slice = [item for item in *items[-1,1,-1]]
984```
985
986</YueDisplay>
987
988### Slicing Expression 473### Slicing Expression
989 474
990Slicing can also be used as an expression. This is useful for getting a sub-list of a table. 475Slicing can also be used as an expression. This is useful for getting a sub-list of a table.
@@ -997,18 +482,6 @@ sub_list = items[2, 4]
997last_four_items = items[-4, -1] 482last_four_items = items[-4, -1]
998``` 483```
999 484
1000<YueDisplay>
1001
1002```yue
1003-- take the 2nd and 4th items as a new list
1004sub_list = items[2, 4]
1005
1006-- take the last 4 items
1007last_four_items = items[-4, -1]
1008```
1009
1010</YueDisplay>
1011
1012# Object Oriented Programming 485# Object Oriented Programming
1013 486
1014In these examples, the generated Lua code may appear overwhelming. It is best to focus on the meaning of the YueScript code at first, then look into the Lua code if you wish to know the implementation details. 487In these examples, the generated Lua code may appear overwhelming. It is best to focus on the meaning of the YueScript code at first, then look into the Lua code if you wish to know the implementation details.
@@ -1027,22 +500,6 @@ class Inventory
1027 @items[name] = 1 500 @items[name] = 1
1028``` 501```
1029 502
1030<YueDisplay>
1031
1032```yue
1033class Inventory
1034 new: =>
1035 @items = {}
1036
1037 add_item: (name) =>
1038 if @items[name]
1039 @items[name] += 1
1040 else
1041 @items[name] = 1
1042```
1043
1044</YueDisplay>
1045
1046A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed. 503A class is declared with a class statement followed by a table-like declaration where all of the methods and properties are listed.
1047 504
1048The new property is special in that it will become the constructor. 505The new property is special in that it will become the constructor.
@@ -1059,16 +516,6 @@ inv\add_item "t-shirt"
1059inv\add_item "pants" 516inv\add_item "pants"
1060``` 517```
1061 518
1062<YueDisplay>
1063
1064```yue
1065inv = Inventory!
1066inv\add_item "t-shirt"
1067inv\add_item "pants"
1068```
1069
1070</YueDisplay>
1071
1072Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used. 519Because the instance of the class needs to be sent to the methods when they are called, the \ operator is used.
1073 520
1074All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur. 521All properties of a class are shared among the instances. This is fine for functions, but for other types of objects, undesired results may occur.
@@ -1091,26 +538,6 @@ b\give_item "shirt"
1091print item for item in *a.clothes 538print item for item in *a.clothes
1092``` 539```
1093 540
1094<YueDisplay>
1095
1096```yue
1097class Person
1098 clothes: []
1099 give_item: (name) =>
1100 table.insert @clothes, name
1101
1102a = Person!
1103b = Person!
1104
1105a\give_item "pants"
1106b\give_item "shirt"
1107
1108-- will print both pants and shirt
1109print item for item in *a.clothes
1110```
1111
1112</YueDisplay>
1113
1114The proper way to avoid this problem is to create the mutable state of the object in the constructor: 541The proper way to avoid this problem is to create the mutable state of the object in the constructor:
1115 542
1116```yuescript 543```yuescript
@@ -1119,16 +546,6 @@ class Person
1119 @clothes = [] 546 @clothes = []
1120``` 547```
1121 548
1122<YueDisplay>
1123
1124```yue
1125class Person
1126 new: =>
1127 @clothes = []
1128```
1129
1130</YueDisplay>
1131
1132## Inheritance 549## Inheritance
1133 550
1134The extends keyword can be used in a class declaration to inherit the properties and methods from another class. 551The extends keyword can be used in a class declaration to inherit the properties and methods from another class.
@@ -1141,18 +558,6 @@ class BackPack extends Inventory
1141 super name 558 super name
1142``` 559```
1143 560
1144<YueDisplay>
1145
1146```yue
1147class BackPack extends Inventory
1148 size: 10
1149 add_item: (name) =>
1150 if #@items > size then error "backpack is full"
1151 super name
1152```
1153
1154</YueDisplay>
1155
1156Here we extend our Inventory class, and limit the amount of items it can carry. 561Here we extend our Inventory class, and limit the amount of items it can carry.
1157 562
1158In this example, we don't define a constructor on the subclass, so the parent class' constructor is called when we make a new instance. If we did define a constructor then we can use the super method to call the parent constructor. 563In this example, we don't define a constructor on the subclass, so the parent class' constructor is called when we make a new instance. If we did define a constructor then we can use the super method to call the parent constructor.
@@ -1168,19 +573,6 @@ class Shelf
1168class Cupboard extends Shelf 573class Cupboard extends Shelf
1169``` 574```
1170 575
1171<YueDisplay>
1172
1173```yue
1174class Shelf
1175 @__inherited: (child) =>
1176 print @__name, "was inherited by", child.__name
1177
1178-- will print: Shelf was inherited by Cupboard
1179class Cupboard extends Shelf
1180```
1181
1182</YueDisplay>
1183
1184## Super 576## Super
1185 577
1186**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. 578**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.
@@ -1207,22 +599,6 @@ class MyClass extends ParentClass
1207 assert super == ParentClass 599 assert super == ParentClass
1208``` 600```
1209 601
1210<YueDisplay>
1211
1212```yue
1213class MyClass extends ParentClass
1214 a_method: =>
1215 -- the following have the same effect:
1216 super "hello", "world"
1217 super\a_method "hello", "world"
1218 super.a_method self, "hello", "world"
1219
1220 -- super as a value is equal to the parent class:
1221 assert super == ParentClass
1222```
1223
1224</YueDisplay>
1225
1226**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. 602**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.
1227 603
1228## Types 604## Types
@@ -1236,17 +612,6 @@ assert b.__class == BackPack
1236print BackPack.size -- prints 10 612print BackPack.size -- prints 10
1237``` 613```
1238 614
1239<YueDisplay>
1240
1241```yue
1242b = BackPack!
1243assert b.__class == BackPack
1244
1245print BackPack.size -- prints 10
1246```
1247
1248</YueDisplay>
1249
1250## Class Objects 615## Class Objects
1251 616
1252The class object is what we create when we use a class statement. The class object is stored in a variable of the same name of the class. 617The class object is what we create when we use a class statement. The class object is stored in a variable of the same name of the class.
@@ -1267,14 +632,6 @@ The name of the class as when it was declared is stored as a string in the \_\_n
1267print BackPack.__name -- prints Backpack 632print BackPack.__name -- prints Backpack
1268``` 633```
1269 634
1270<YueDisplay>
1271
1272```yue
1273print BackPack.__name -- prints Backpack
1274```
1275
1276</YueDisplay>
1277
1278The base object is stored in \_\_base. We can modify this table to add functionality to instances that have already been created and ones that are yet to be created. 635The base object is stored in \_\_base. We can modify this table to add functionality to instances that have already been created and ones that are yet to be created.
1279 636
1280If the class extends from anything, the parent class object is stored in \_\_parent. 637If the class extends from anything, the parent class object is stored in \_\_parent.
@@ -1293,20 +650,6 @@ Things\some_func!
1293assert Things().some_func == nil 650assert Things().some_func == nil
1294``` 651```
1295 652
1296<YueDisplay>
1297
1298```yue
1299class Things
1300 @some_func: => print "Hello from", @__name
1301
1302Things\some_func!
1303
1304-- class variables not visible in instances
1305assert Things().some_func == nil
1306```
1307
1308</YueDisplay>
1309
1310In expressions, we can use @@ to access a value that is stored in the **class of self. Thus, @@hello is shorthand for self.**class.hello. 653In expressions, we can use @@ to access a value that is stored in the **class of self. Thus, @@hello is shorthand for self.**class.hello.
1311 654
1312```yuescript 655```yuescript
@@ -1322,37 +665,12 @@ Counter!
1322print Counter.count -- prints 2 665print Counter.count -- prints 2
1323``` 666```
1324 667
1325<YueDisplay>
1326
1327```yue
1328class Counter
1329 @count: 0
1330
1331 new: =>
1332 @@count += 1
1333
1334Counter!
1335Counter!
1336
1337print Counter.count -- prints 2
1338```
1339
1340</YueDisplay>
1341
1342The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax. 668The calling semantics of @@ are similar to @. Calling a @@ name will pass the class in as the first argument using Lua's colon syntax.
1343 669
1344```yuescript 670```yuescript
1345@@hello 1,2,3,4 671@@hello 1,2,3,4
1346``` 672```
1347 673
1348<YueDisplay>
1349
1350```yue
1351@@hello 1,2,3,4
1352```
1353
1354</YueDisplay>
1355
1356## Class Declaration Statements 674## Class Declaration Statements
1357 675
1358In the body of a class declaration, we can have normal expressions in addition to key/value pairs. In this context, self is equal to the class object. 676In the body of a class declaration, we can have normal expressions in addition to key/value pairs. In this context, self is equal to the class object.
@@ -1364,15 +682,6 @@ class Things
1364 @class_var = "hello world" 682 @class_var = "hello world"
1365``` 683```
1366 684
1367<YueDisplay>
1368
1369```yue
1370class Things
1371 @class_var = "hello world"
1372```
1373
1374</YueDisplay>
1375
1376These expressions are executed after all the properties have been added to the base. 685These expressions are executed after all the properties have been added to the base.
1377 686
1378All variables declared in the body of the class are local to the classes properties. This is convenient for placing private values or helper functions that only the class methods can access: 687All variables declared in the body of the class are local to the classes properties. This is convenient for placing private values or helper functions that only the class methods can access:
@@ -1386,19 +695,6 @@ class MoreThings
1386 log "hello world: " .. secret 695 log "hello world: " .. secret
1387``` 696```
1388 697
1389<YueDisplay>
1390
1391```yue
1392class MoreThings
1393 secret = 123
1394 log = (msg) -> print "LOG:", msg
1395
1396 some_method: =>
1397 log "hello world: " .. secret
1398```
1399
1400</YueDisplay>
1401
1402## @ and @@ Values 698## @ and @@ Values
1403 699
1404When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.\_\_class. 700When @ and @@ are prefixed in front of a name they represent, respectively, that name accessed in self and self.\_\_class.
@@ -1410,29 +706,12 @@ assert @ == self
1410assert @@ == self.__class 706assert @@ == self.__class
1411``` 707```
1412 708
1413<YueDisplay>
1414
1415```yue
1416assert @ == self
1417assert @@ == self.__class
1418```
1419
1420</YueDisplay>
1421
1422For example, a quick way to create a new instance of the same class from an instance method using @@: 709For example, a quick way to create a new instance of the same class from an instance method using @@:
1423 710
1424```yuescript 711```yuescript
1425some_instance_method = (...) => @@ ... 712some_instance_method = (...) => @@ ...
1426``` 713```
1427 714
1428<YueDisplay>
1429
1430```yue
1431some_instance_method = (...) => @@ ...
1432```
1433
1434</YueDisplay>
1435
1436## Constructor Property Promotion 715## Constructor Property Promotion
1437 716
1438To reduce the boilerplate code for definition of simple value objects. You can write a simple class like: 717To reduce the boilerplate code for definition of simple value objects. You can write a simple class like:
@@ -1451,24 +730,6 @@ class Something
1451 @@baz = baz 730 @@baz = baz
1452``` 731```
1453 732
1454<YueDisplay>
1455
1456```yue
1457class Something
1458 new: (@foo, @bar, @@biz, @@baz) =>
1459
1460-- Which is short for
1461
1462class Something
1463 new: (foo, bar, biz, baz) =>
1464 @foo = foo
1465 @bar = bar
1466 @@biz = biz
1467 @@baz = baz
1468```
1469
1470</YueDisplay>
1471
1472You can also use this syntax for a common function to initialize a object's fields. 733You can also use this syntax for a common function to initialize a object's fields.
1473 734
1474```yuescript 735```yuescript
@@ -1477,16 +738,6 @@ obj = new {}, 123, "abc"
1477print obj 738print obj
1478``` 739```
1479 740
1480<YueDisplay>
1481
1482```yue
1483new = (@fieldA, @fieldB) => @
1484obj = new {}, 123, "abc"
1485print obj
1486```
1487
1488</YueDisplay>
1489
1490## Class Expressions 741## Class Expressions
1491 742
1492The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned. 743The class syntax can also be used as an expression which can be assigned to a variable or explicitly returned.
@@ -1497,16 +748,6 @@ x = class Bucket
1497 add_drop: => @drops += 1 748 add_drop: => @drops += 1
1498``` 749```
1499 750
1500<YueDisplay>
1501
1502```yue
1503x = class Bucket
1504 drops: 0
1505 add_drop: => @drops += 1
1506```
1507
1508</YueDisplay>
1509
1510## Anonymous classes 751## Anonymous classes
1511 752
1512The name can be left out when declaring a class. The \_\_name attribute will be nil, unless the class expression is in an assignment. The name on the left hand side of the assignment is used instead of nil. 753The name can be left out when declaring a class. The \_\_name attribute will be nil, unless the class expression is in an assignment. The name on the left hand side of the assignment is used instead of nil.
@@ -1518,31 +759,12 @@ BigBucket = class extends Bucket
1518assert Bucket.__name == "BigBucket" 759assert Bucket.__name == "BigBucket"
1519``` 760```
1520 761
1521<YueDisplay>
1522
1523```yue
1524BigBucket = class extends Bucket
1525 add_drop: => @drops += 10
1526
1527assert Bucket.__name == "BigBucket"
1528```
1529
1530</YueDisplay>
1531
1532You can even leave off the body, meaning you can write a blank anonymous class like this: 762You can even leave off the body, meaning you can write a blank anonymous class like this:
1533 763
1534```yuescript 764```yuescript
1535x = class 765x = class
1536``` 766```
1537 767
1538<YueDisplay>
1539
1540```yue
1541x = class
1542```
1543
1544</YueDisplay>
1545
1546## Class Mixing 768## Class Mixing
1547 769
1548You can do mixing with keyword `using` to copy functions from either a plain table or a predefined class object into your new class. When doing mixing with a plain table, you can override the class indexing function (metamethod `__index`) to your customized implementation. When doing mixing with an existing class object, the class object's metamethods won't be copied. 770You can do mixing with keyword `using` to copy functions from either a plain table or a predefined class object into your new class. When doing mixing with a plain table, you can override the class indexing function (metamethod `__index`) to your customized implementation. When doing mixing with an existing class object, the class object's metamethods won't be copied.
@@ -1565,28 +787,6 @@ y\func!
1565assert y.__class.__parent ~= X -- X is not parent of Y 787assert y.__class.__parent ~= X -- X is not parent of Y
1566``` 788```
1567 789
1568<YueDisplay>
1569
1570```yue
1571MyIndex = __index: var: 1
1572
1573class X using MyIndex
1574 func: =>
1575 print 123
1576
1577x = X!
1578print x.var
1579
1580class Y using X
1581
1582y = Y!
1583y\func!
1584
1585assert y.__class.__parent ~= X -- X is not parent of Y
1586```
1587
1588</YueDisplay>
1589
1590# With Statement 790# With Statement
1591 791
1592A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it. 792A common pattern involving the creation of an object is calling a series of functions and setting a series of properties immediately after creating it.
@@ -1605,18 +805,6 @@ with Person!
1605 print .name 805 print .name
1606``` 806```
1607 807
1608<YueDisplay>
1609
1610```yue
1611with Person!
1612 .name = "Oswald"
1613 \add_relative my_dad
1614 \save!
1615 print .name
1616```
1617
1618</YueDisplay>
1619
1620The with statement can also be used as an expression which returns the value it has been giving access to. 808The with statement can also be used as an expression which returns the value it has been giving access to.
1621 809
1622```yuescript 810```yuescript
@@ -1624,15 +812,6 @@ file = with File "favorite_foods.txt"
1624 \set_encoding "utf8" 812 \set_encoding "utf8"
1625``` 813```
1626 814
1627<YueDisplay>
1628
1629```yue
1630file = with File "favorite_foods.txt"
1631 \set_encoding "utf8"
1632```
1633
1634</YueDisplay>
1635
1636`with` expressions support `break` with one value: 815`with` expressions support `break` with one value:
1637 816
1638```yuescript 817```yuescript
@@ -1640,15 +819,6 @@ result = with obj
1640 break .value 819 break .value
1641``` 820```
1642 821
1643<YueDisplay>
1644
1645```yue
1646result = with obj
1647 break .value
1648```
1649
1650</YueDisplay>
1651
1652After `break value` is used inside `with`, the `with` expression no longer returns its target object. Instead, it returns the value from `break`. 822After `break value` is used inside `with`, the `with` expression no longer returns its target object. Instead, it returns the value from `break`.
1653 823
1654```yuescript 824```yuescript
@@ -1661,20 +831,6 @@ b = with obj
1661-- b is .x, not obj 831-- b is .x, not obj
1662``` 832```
1663 833
1664<YueDisplay>
1665
1666```yue
1667a = with obj
1668 .x = 1
1669-- a is obj
1670
1671b = with obj
1672 break .x
1673-- b is .x, not obj
1674```
1675
1676</YueDisplay>
1677
1678Unlike `for` / `while` / `repeat` / `do`, `with` only supports one break value. 834Unlike `for` / `while` / `repeat` / `do`, `with` only supports one break value.
1679 835
1680Or… 836Or…
@@ -1688,19 +844,6 @@ create_person = (name, relatives) ->
1688me = create_person "Leaf", [dad, mother, sister] 844me = create_person "Leaf", [dad, mother, sister]
1689``` 845```
1690 846
1691<YueDisplay>
1692
1693```yue
1694create_person = (name, relatives) ->
1695 with Person!
1696 .name = name
1697 \add_relative relative for relative in *relatives
1698
1699me = create_person "Leaf", [dad, mother, sister]
1700```
1701
1702</YueDisplay>
1703
1704In this usage, with can be seen as a special form of the K combinator. 847In this usage, with can be seen as a special form of the K combinator.
1705 848
1706The expression in the with statement can also be an assignment, if you want to give a name to the expression. 849The expression in the with statement can also be an assignment, if you want to give a name to the expression.
@@ -1711,16 +854,6 @@ with str := "Hello"
1711 print "upper:", \upper! 854 print "upper:", \upper!
1712``` 855```
1713 856
1714<YueDisplay>
1715
1716```yue
1717with str := "Hello"
1718 print "original:", str
1719 print "upper:", \upper!
1720```
1721
1722</YueDisplay>
1723
1724You can access special keys with `[]` in a `with` statement. 857You can access special keys with `[]` in a `with` statement.
1725 858
1726```yuescript 859```yuescript
@@ -1733,20 +866,6 @@ with tb
1733 [] = "abc" -- appending to "tb" 866 [] = "abc" -- appending to "tb"
1734``` 867```
1735 868
1736<YueDisplay>
1737
1738```yue
1739with tb
1740 [1] = 1
1741 print [2]
1742 with [abc]
1743 [3] = [2]\func!
1744 ["key-name"] = value
1745 [] = "abc" -- appending to "tb"
1746```
1747
1748</YueDisplay>
1749
1750`with?` is an enhanced version of `with` syntax, which introduces an existential check to safely access objects that may be nil without explicit null checks. 869`with?` is an enhanced version of `with` syntax, which introduces an existential check to safely access objects that may be nil without explicit null checks.
1751 870
1752```yuescript 871```yuescript
@@ -1754,15 +873,6 @@ with? obj
1754 print obj.name 873 print obj.name
1755``` 874```
1756 875
1757<YueDisplay>
1758
1759```yue
1760with? obj
1761 print obj.name
1762```
1763
1764</YueDisplay>
1765
1766# Assignment 876# Assignment
1767 877
1768The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement. 878The variable is dynamic typed and is defined as local by default. But you can change the scope of declaration by **local** and **global** statement.
@@ -1773,16 +883,6 @@ a, b, c = 1, 2, 3
1773hello = 123 -- uses the existing variable 883hello = 123 -- uses the existing variable
1774``` 884```
1775 885
1776<YueDisplay>
1777
1778```yue
1779hello = "world"
1780a, b, c = 1, 2, 3
1781hello = 123 -- uses the existing variable
1782```
1783
1784</YueDisplay>
1785
1786## Perform Update 886## Perform Update
1787 887
1788You can perform update assignment with many binary operators. 888You can perform update assignment with many binary operators.
@@ -1798,21 +898,6 @@ s ..= "world" -- will add a new local if local variable is not exist
1798arg or= "default value" 898arg or= "default value"
1799``` 899```
1800 900
1801<YueDisplay>
1802
1803```yue
1804x = 1
1805x += 1
1806x -= 1
1807x *= 10
1808x /= 10
1809x %= 10
1810s ..= "world" -- will add a new local if local variable is not exist
1811arg or= "default value"
1812```
1813
1814</YueDisplay>
1815
1816## Chaining Assignment 901## Chaining Assignment
1817 902
1818You can do chaining assignment to assign multiple items to hold the same value. 903You can do chaining assignment to assign multiple items to hold the same value.
@@ -1822,15 +907,6 @@ a = b = c = d = e = 0
1822x = y = z = f! 907x = y = z = f!
1823``` 908```
1824 909
1825<YueDisplay>
1826
1827```yue
1828a = b = c = d = e = 0
1829x = y = z = f!
1830```
1831
1832</YueDisplay>
1833
1834## Explicit Locals 910## Explicit Locals
1835 911
1836```yuescript 912```yuescript
@@ -1850,27 +926,6 @@ do
1850 B = 2 926 B = 2
1851``` 927```
1852 928
1853<YueDisplay>
1854
1855```yue
1856do
1857 local a = 1
1858 local *
1859 print "forward declare all variables as locals"
1860 x = -> 1 + y + z
1861 y, z = 2, 3
1862 global instance = Item\new!
1863
1864do
1865 local X = 1
1866 local ^
1867 print "only forward declare upper case variables"
1868 a = 1
1869 B = 2
1870```
1871
1872</YueDisplay>
1873
1874## Explicit Globals 929## Explicit Globals
1875 930
1876```yuescript 931```yuescript
@@ -1890,27 +945,6 @@ do
1890 local Temp = "a local value" 945 local Temp = "a local value"
1891``` 946```
1892 947
1893<YueDisplay>
1894
1895```yue
1896do
1897 global a = 1
1898 global *
1899 print "declare all variables as globals"
1900 x = -> 1 + y + z
1901 y, z = 2, 3
1902
1903do
1904 global X = 1
1905 global ^
1906 print "only declare upper case variables as globals"
1907 a = 1
1908 B = 2
1909 local Temp = "a local value"
1910```
1911
1912</YueDisplay>
1913
1914# Varargs Assignment 948# Varargs Assignment
1915 949
1916You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way. 950You can assign the results returned from a function to a varargs symbol `...`. And then access its content using the Lua way.
@@ -1924,19 +958,6 @@ first = select 1, ...
1924print ok, count, first 958print ok, count, first
1925``` 959```
1926 960
1927<YueDisplay>
1928
1929```yue
1930list = [1, 2, 3, 4, 5]
1931fn = (ok) -> ok, table.unpack list
1932ok, ... = fn true
1933count = select '#', ...
1934first = select 1, ...
1935print ok, count, first
1936```
1937
1938</YueDisplay>
1939
1940# If Assignment 961# If Assignment
1941 962
1942`if` and `elseif` blocks can take an assignment in place of a conditional expression. Upon evaluating the conditional, the assignment will take place and the value that was assigned to will be used as the conditional expression. The assigned variable is only in scope for the body of the conditional, meaning it is never available if the value is not truthy. And you have to use "the walrus operator" `:=` instead of `=` to do assignment. 963`if` and `elseif` blocks can take an assignment in place of a conditional expression. Upon evaluating the conditional, the assignment will take place and the value that was assigned to will be used as the conditional expression. The assigned variable is only in scope for the body of the conditional, meaning it is never available if the value is not truthy. And you have to use "the walrus operator" `:=` instead of `=` to do assignment.
@@ -1946,15 +967,6 @@ if user := database.find_user "moon"
1946 print user.name 967 print user.name
1947``` 968```
1948 969
1949<YueDisplay>
1950
1951```yue
1952if user := database.find_user "moon"
1953 print user.name
1954```
1955
1956</YueDisplay>
1957
1958```yuescript 970```yuescript
1959if hello := os.getenv "hello" 971if hello := os.getenv "hello"
1960 print "You have hello", hello 972 print "You have hello", hello
@@ -1964,19 +976,6 @@ else
1964 print "nothing :(" 976 print "nothing :("
1965``` 977```
1966 978
1967<YueDisplay>
1968
1969```yue
1970if hello := os.getenv "hello"
1971 print "You have hello", hello
1972elseif world := os.getenv "world"
1973 print "you have world", world
1974else
1975 print "nothing :("
1976```
1977
1978</YueDisplay>
1979
1980If assignment with multiple return values. Only the first value is getting checked, other values are scoped. 979If assignment with multiple return values. Only the first value is getting checked, other values are scoped.
1981 980
1982```yuescript 981```yuescript
@@ -1985,16 +984,6 @@ if success, result := pcall -> "get result without problems"
1985print "OK" 984print "OK"
1986``` 985```
1987 986
1988<YueDisplay>
1989
1990```yue
1991if success, result := pcall -> "get result without problems"
1992 print result -- variable result is scoped
1993print "OK"
1994```
1995
1996</YueDisplay>
1997
1998## While Assignment 987## While Assignment
1999 988
2000You can also use if assignment in a while loop to get the value as the loop condition. 989You can also use if assignment in a while loop to get the value as the loop condition.
@@ -2005,16 +994,6 @@ while byte := stream\read_one!
2005 print byte 994 print byte
2006``` 995```
2007 996
2008<YueDisplay>
2009
2010```yue
2011while byte := stream\read_one!
2012 -- do something with the byte
2013 print byte
2014```
2015
2016</YueDisplay>
2017
2018# Destructuring Assignment 997# Destructuring Assignment
2019 998
2020Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables. 999Destructuring assignment is a way to quickly extract values from a table by their name or position in array based tables.
@@ -2030,17 +1009,6 @@ thing = [1, 2]
2030print a, b 1009print a, b
2031``` 1010```
2032 1011
2033<YueDisplay>
2034
2035```yue
2036thing = [1, 2]
2037
2038[a, b] = thing
2039print a, b
2040```
2041
2042</YueDisplay>
2043
2044In the destructuring table literal, the key represents the key to read from the right hand side, and the value represents the name the read value will be assigned to. 1012In the destructuring table literal, the key represents the key to read from the right hand side, and the value represents the name the read value will be assigned to.
2045 1013
2046```yuescript 1014```yuescript
@@ -2056,23 +1024,6 @@ print hello, the_day
2056:day = obj -- OK to do simple destructuring without braces 1024:day = obj -- OK to do simple destructuring without braces
2057``` 1025```
2058 1026
2059<YueDisplay>
2060
2061```yue
2062obj = {
2063 hello: "world"
2064 day: "tuesday"
2065 length: 20
2066}
2067
2068{hello: hello, day: the_day} = obj
2069print hello, the_day
2070
2071:day = obj -- OK to do simple destructuring without braces
2072```
2073
2074</YueDisplay>
2075
2076This also works with nested data structures as well: 1027This also works with nested data structures as well:
2077 1028
2078```yuescript 1029```yuescript
@@ -2088,23 +1039,6 @@ obj2 = {
2088print first, second, color 1039print first, second, color
2089``` 1040```
2090 1041
2091<YueDisplay>
2092
2093```yue
2094obj2 = {
2095 numbers: [1, 2, 3, 4]
2096 properties: {
2097 color: "green"
2098 height: 13.5
2099 }
2100}
2101
2102{numbers: [first, second], properties: {color: color}} = obj2
2103print first, second, color
2104```
2105
2106</YueDisplay>
2107
2108If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example: 1042If the destructuring statement is complicated, feel free to spread it out over a few lines. A slightly more complicated example:
2109 1043
2110```yuescript 1044```yuescript
@@ -2116,75 +1050,30 @@ If the destructuring statement is complicated, feel free to spread it out over a
2116} = obj2 1050} = obj2
2117``` 1051```
2118 1052
2119<YueDisplay>
2120
2121```yue
2122{
2123 numbers: [first, second]
2124 properties: {
2125 color: color
2126 }
2127} = obj2
2128```
2129
2130</YueDisplay>
2131
2132It's common to extract values from at table and assign them the local variables that have the same name as the key. In order to avoid repetition we can use the **:** prefix operator: 1053It's common to extract values from at table and assign them the local variables that have the same name as the key. In order to avoid repetition we can use the **:** prefix operator:
2133 1054
2134```yuescript 1055```yuescript
2135{:concat, :insert} = table 1056{:concat, :insert} = table
2136``` 1057```
2137 1058
2138<YueDisplay>
2139
2140```yue
2141{:concat, :insert} = table
2142```
2143
2144</YueDisplay>
2145
2146This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax: 1059This is effectively the same as import, but we can rename fields we want to extract by mixing the syntax:
2147 1060
2148```yuescript 1061```yuescript
2149{:mix, :max, random: rand} = math 1062{:mix, :max, random: rand} = math
2150``` 1063```
2151 1064
2152<YueDisplay>
2153
2154```yue
2155{:mix, :max, random: rand} = math
2156```
2157
2158</YueDisplay>
2159
2160You can write default values while doing destructuring like: 1065You can write default values while doing destructuring like:
2161 1066
2162```yuescript 1067```yuescript
2163{:name = "nameless", :job = "jobless"} = person 1068{:name = "nameless", :job = "jobless"} = person
2164``` 1069```
2165 1070
2166<YueDisplay>
2167
2168```yue
2169{:name = "nameless", :job = "jobless"} = person
2170```
2171
2172</YueDisplay>
2173
2174You can use `_` as placeholder when doing a list destructuring: 1071You can use `_` as placeholder when doing a list destructuring:
2175 1072
2176```yuescript 1073```yuescript
2177[_, two, _, four] = items 1074[_, two, _, four] = items
2178``` 1075```
2179 1076
2180<YueDisplay>
2181
2182```yue
2183[_, two, _, four] = items
2184```
2185
2186</YueDisplay>
2187
2188## Range Destructuring 1077## Range Destructuring
2189 1078
2190You can use the spread operator `...` in list destructuring to capture a range of values. This is useful when you want to extract specific elements from the beginning and end of a list while collecting the rest in between. 1079You can use the spread operator `...` in list destructuring to capture a range of values. This is useful when you want to extract specific elements from the beginning and end of a list while collecting the rest in between.
@@ -2197,18 +1086,6 @@ print bulk -- prints: {"second", "third", "fourth"}
2197print last -- prints: last 1086print last -- prints: last
2198``` 1087```
2199 1088
2200<YueDisplay>
2201
2202```yue
2203orders = ["first", "second", "third", "fourth", "last"]
2204[first, ...bulk, last] = orders
2205print first -- prints: first
2206print bulk -- prints: {"second", "third", "fourth"}
2207print last -- prints: last
2208```
2209
2210</YueDisplay>
2211
2212The spread operator can be used in different positions to capture different ranges, and you can use `_` as a placeholder for the values you don't want to capture: 1089The spread operator can be used in different positions to capture different ranges, and you can use `_` as a placeholder for the values you don't want to capture:
2213 1090
2214```yuescript 1091```yuescript
@@ -2222,21 +1099,6 @@ The spread operator can be used in different positions to capture different rang
2222[first, ..._, last] = orders 1099[first, ..._, last] = orders
2223``` 1100```
2224 1101
2225<YueDisplay>
2226
2227```yue
2228-- Capture everything after first element
2229[first, ...rest] = orders
2230
2231-- Capture everything before last element
2232[...start, last] = orders
2233
2234-- Capture things except the middle elements
2235[first, ..._, last] = orders
2236```
2237
2238</YueDisplay>
2239
2240## Destructuring In Other Places 1102## Destructuring In Other Places
2241 1103
2242Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop: 1104Destructuring can also show up in places where an assignment implicitly takes place. An example of this is a for loop:
@@ -2251,20 +1113,6 @@ for [left, right] in *tuples
2251 print left, right 1113 print left, right
2252``` 1114```
2253 1115
2254<YueDisplay>
2255
2256```yue
2257tuples = [
2258 ["hello", "world"]
2259 ["egg", "head"]
2260]
2261
2262for [left, right] in *tuples
2263 print left, right
2264```
2265
2266</YueDisplay>
2267
2268We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure. 1116We know each element in the array table is a two item tuple, so we can unpack it directly in the names clause of the for statement using a destructure.
2269 1117
2270# The Using Clause; Controlling Destructive Assignment 1118# The Using Clause; Controlling Destructive Assignment
@@ -2287,26 +1135,6 @@ my_func!
2287print i -- will print 0 1135print i -- will print 0
2288``` 1136```
2289 1137
2290<YueDisplay>
2291
2292```yue
2293i = 100
2294
2295-- many lines of code...
2296
2297my_func = ->
2298 i = 10
2299 while i > 0
2300 print i
2301 i -= 1
2302
2303my_func!
2304
2305print i -- will print 0
2306```
2307
2308</YueDisplay>
2309
2310In 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 clear what names have already been declared. 1138In 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 clear what names have already been declared.
2311 1139
2312It would be helpful to say which variables from the enclosing scope we intend on change, in order to prevent us from changing others by accident. 1140It would be helpful to say which variables from the enclosing scope we intend on change, in order to prevent us from changing others by accident.
@@ -2323,20 +1151,6 @@ my_func!
2323print i -- prints 100, i is unaffected 1151print i -- prints 100, i is unaffected
2324``` 1152```
2325 1153
2326<YueDisplay>
2327
2328```yue
2329i = 100
2330
2331my_func = (using nil) ->
2332 i = "hello" -- a new local variable is created here
2333
2334my_func!
2335print i -- prints 100, i is unaffected
2336```
2337
2338</YueDisplay>
2339
2340Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified: 1154Multiple names can be separated by commas. Closure values can still be accessed, they just cant be modified:
2341 1155
2342```yuescript 1156```yuescript
@@ -2352,23 +1166,6 @@ my_func(22)
2352print i, k -- these have been updated 1166print i, k -- these have been updated
2353``` 1167```
2354 1168
2355<YueDisplay>
2356
2357```yue
2358tmp = 1213
2359i, k = 100, 50
2360
2361my_func = (add using k, i) ->
2362 tmp = tmp + add -- a new local tmp is created
2363 i += tmp
2364 k += tmp
2365
2366my_func(22)
2367print i, k -- these have been updated
2368```
2369
2370</YueDisplay>
2371
2372# Usage 1169# Usage
2373 1170
2374## Lua Module 1171## Lua Module
@@ -2537,55 +1334,6 @@ with apple
2537export 🌛 = "Script of Moon" 1334export 🌛 = "Script of Moon"
2538``` 1335```
2539 1336
2540<YueDisplay>
2541
2542```yue
2543-- import syntax
2544import p, to_lua from "yue"
2545
2546-- object literals
2547inventory =
2548 equipment:
2549 - "sword"
2550 - "shield"
2551 items:
2552 - name: "potion"
2553 count: 10
2554 - name: "bread"
2555 count: 3
2556
2557-- list comprehension
2558map = (arr, action) ->
2559 [action item for item in *arr]
2560
2561filter = (arr, cond) ->
2562 [item for item in *arr when cond item]
2563
2564reduce = (arr, init, action): init ->
2565 init = action init, item for item in *arr
2566
2567-- pipe operator
2568[1, 2, 3]
2569 |> map (x) -> x * 2
2570 |> filter (x) -> x > 4
2571 |> reduce 0, (a, b) -> a + b
2572 |> print
2573
2574-- metatable manipulation
2575apple =
2576 size: 15
2577 <index>:
2578 color: 0x00ffff
2579
2580with apple
2581 p .size, .color, .<index> if .<>?
2582
2583-- js-like export syntax
2584export 🌛 = "Script of Moon"
2585```
2586
2587</YueDisplay>
2588
2589## About Dora SSR 1337## About Dora SSR
2590 1338
2591YueScript is being developed and maintained alongside the open-source game engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). It has been used to create engine tools, game demos and prototypes, validating its capabilities in real-world scenarios while enhancing the Dora SSR development experience. 1339YueScript is being developed and maintained alongside the open-source game engine [Dora SSR](https://github.com/Dora-SSR/Dora-SSR). It has been used to create engine tools, game demos and prototypes, validating its capabilities in real-world scenarios while enhancing the Dora SSR development experience.
@@ -2644,18 +1392,6 @@ else
2644 print "No coins" 1392 print "No coins"
2645``` 1393```
2646 1394
2647<YueDisplay>
2648
2649```yue
2650have_coins = false
2651if have_coins
2652 print "Got coins"
2653else
2654 print "No coins"
2655```
2656
2657</YueDisplay>
2658
2659A short syntax for single statements can also be used: 1395A short syntax for single statements can also be used:
2660 1396
2661```yuescript 1397```yuescript
@@ -2663,15 +1399,6 @@ have_coins = false
2663if have_coins then print "Got coins" else print "No coins" 1399if have_coins then print "Got coins" else print "No coins"
2664``` 1400```
2665 1401
2666<YueDisplay>
2667
2668```yue
2669have_coins = false
2670if have_coins then print "Got coins" else print "No coins"
2671```
2672
2673</YueDisplay>
2674
2675Because if statements can be used as expressions, this can also be written as: 1402Because if statements can be used as expressions, this can also be written as:
2676 1403
2677```yuescript 1404```yuescript
@@ -2679,15 +1406,6 @@ have_coins = false
2679print if have_coins then "Got coins" else "No coins" 1406print if have_coins then "Got coins" else "No coins"
2680``` 1407```
2681 1408
2682<YueDisplay>
2683
2684```yue
2685have_coins = false
2686print if have_coins then "Got coins" else "No coins"
2687```
2688
2689</YueDisplay>
2690
2691Conditionals can also be used in return statements and assignments: 1409Conditionals can also be used in return statements and assignments:
2692 1410
2693```yuescript 1411```yuescript
@@ -2705,25 +1423,6 @@ else
2705print message -- prints: I am very tall 1423print message -- prints: I am very tall
2706``` 1424```
2707 1425
2708<YueDisplay>
2709
2710```yue
2711is_tall = (name) ->
2712 if name == "Rob"
2713 true
2714 else
2715 false
2716
2717message = if is_tall "Rob"
2718 "I am very tall"
2719else
2720 "I am not so tall"
2721
2722print message -- prints: I am very tall
2723```
2724
2725</YueDisplay>
2726
2727The opposite of if is unless: 1426The opposite of if is unless:
2728 1427
2729```yuescript 1428```yuescript
@@ -2731,27 +1430,10 @@ unless os.date("%A") == "Monday"
2731 print "it is not Monday!" 1430 print "it is not Monday!"
2732``` 1431```
2733 1432
2734<YueDisplay>
2735
2736```yue
2737unless os.date("%A") == "Monday"
2738 print "it is not Monday!"
2739```
2740
2741</YueDisplay>
2742
2743```yuescript 1433```yuescript
2744print "You're lucky!" unless math.random! > 0.1 1434print "You're lucky!" unless math.random! > 0.1
2745``` 1435```
2746 1436
2747<YueDisplay>
2748
2749```yue
2750print "You're lucky!" unless math.random! > 0.1
2751```
2752
2753</YueDisplay>
2754
2755## In Expression 1437## In Expression
2756 1438
2757You can write range checking code with an `in-expression`. 1439You can write range checking code with an `in-expression`.
@@ -2766,20 +1448,6 @@ if a in list
2766 print "checking if `a` is in a list" 1448 print "checking if `a` is in a list"
2767``` 1449```
2768 1450
2769<YueDisplay>
2770
2771```yue
2772a = 5
2773
2774if a in [1, 3, 5, 7]
2775 print "checking equality with discrete values"
2776
2777if a in list
2778 print "checking if `a` is in a list"
2779```
2780
2781</YueDisplay>
2782
2783The `in` operator can also be used with tables and supports the `not in` variant for negation: 1451The `in` operator can also be used with tables and supports the `not in` variant for negation:
2784 1452
2785```yuescript 1453```yuescript
@@ -2793,21 +1461,6 @@ not_exist = item not in list
2793check = -> value not in table 1461check = -> value not in table
2794``` 1462```
2795 1463
2796<YueDisplay>
2797
2798```yue
2799has = "foo" in {"bar", "foo"}
2800
2801if a in {1, 2, 3}
2802 print "a is in the table"
2803
2804not_exist = item not in list
2805
2806check = -> value not in table
2807```
2808
2809</YueDisplay>
2810
2811A single-element list or table checks for equality with that element: 1464A single-element list or table checks for equality with that element:
2812 1465
2813```yuescript 1466```yuescript
@@ -2822,22 +1475,6 @@ with tb
2822 c = a in [1] 1475 c = a in [1]
2823``` 1476```
2824 1477
2825<YueDisplay>
2826
2827```yue
2828-- [1,] checks if value == 1
2829c = a in [1,]
2830
2831-- {1} also checks if value == 1
2832c = a in {1}
2833
2834-- Without comma, [1] is indexing (tb[1])
2835with tb
2836 c = a in [1]
2837```
2838
2839</YueDisplay>
2840
2841# For Loop 1478# For Loop
2842 1479
2843There are two for loop forms, just like in Lua. A numeric one and a generic one: 1480There are two for loop forms, just like in Lua. A numeric one and a generic one:
@@ -2853,21 +1490,6 @@ for key, value in pairs object
2853 print key, value 1490 print key, value
2854``` 1491```
2855 1492
2856<YueDisplay>
2857
2858```yue
2859for i = 10, 20
2860 print i
2861
2862for k = 1, 15, 2 -- an optional step provided
2863 print k
2864
2865for key, value in pairs object
2866 print key, value
2867```
2868
2869</YueDisplay>
2870
2871The slicing and **\*** operators can be used, just like with comprehensions: 1493The slicing and **\*** operators can be used, just like with comprehensions:
2872 1494
2873```yuescript 1495```yuescript
@@ -2875,15 +1497,6 @@ for item in *items[2, 4]
2875 print item 1497 print item
2876``` 1498```
2877 1499
2878<YueDisplay>
2879
2880```yue
2881for item in *items[2, 4]
2882 print item
2883```
2884
2885</YueDisplay>
2886
2887A shorter syntax is also available for all variations when the body is only a single line: 1500A shorter syntax is also available for all variations when the body is only a single line:
2888 1501
2889```yuescript 1502```yuescript
@@ -2892,16 +1505,6 @@ for item in *items do print item
2892for j = 1, 10, 3 do print j 1505for j = 1, 10, 3 do print j
2893``` 1506```
2894 1507
2895<YueDisplay>
2896
2897```yue
2898for item in *items do print item
2899
2900for j = 1, 10, 3 do print j
2901```
2902
2903</YueDisplay>
2904
2905A for loop can also be used as an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating array table. 1508A for loop can also be used as an expression. The last statement in the body of the for loop is coerced into an expression and appended to an accumulating array table.
2906 1509
2907Doubling every even number: 1510Doubling every even number:
@@ -2914,18 +1517,6 @@ doubled_evens = for i = 1, 20
2914 i 1517 i
2915``` 1518```
2916 1519
2917<YueDisplay>
2918
2919```yue
2920doubled_evens = for i = 1, 20
2921 if i % 2 == 0
2922 i * 2
2923 else
2924 i
2925```
2926
2927</YueDisplay>
2928
2929In addition, for loops support break with return values, allowing the loop itself to be used as an expression that exits early with meaningful results. 1520In addition, for loops support break with return values, allowing the loop itself to be used as an expression that exits early with meaningful results.
2930 1521
2931For example, to find the first number greater than 10: 1522For example, to find the first number greater than 10:
@@ -2935,15 +1526,6 @@ first_large = for n in *numbers
2935 break n if n > 10 1526 break n if n > 10
2936``` 1527```
2937 1528
2938<YueDisplay>
2939
2940```yue
2941first_large = for n in *numbers
2942 break n if n > 10
2943```
2944
2945</YueDisplay>
2946
2947This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. 1529This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions.
2948 1530
2949For loop expressions can break with multiple values: 1531For loop expressions can break with multiple values:
@@ -2953,15 +1535,6 @@ key, score = for k, v in pairs data
2953 break k, v * 10 if k == "target" 1535 break k, v * 10 if k == "target"
2954``` 1536```
2955 1537
2956<YueDisplay>
2957
2958```yue
2959key, score = for k, v in pairs data
2960 break k, v * 10 if k == "target"
2961```
2962
2963</YueDisplay>
2964
2965You can also filter values by combining the for loop expression with the continue statement. 1538You can also filter values by combining the for loop expression with the continue statement.
2966 1539
2967For 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. 1540For 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.
@@ -2974,18 +1547,6 @@ print func_a! -- prints nil
2974print func_b! -- prints table object 1547print func_b! -- prints table object
2975``` 1548```
2976 1549
2977<YueDisplay>
2978
2979```yue
2980func_a = -> for i = 1, 10 do print i
2981func_b = -> return for i = 1, 10 do i
2982
2983print func_a! -- prints nil
2984print func_b! -- prints table object
2985```
2986
2987</YueDisplay>
2988
2989This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop. 1550This is done to avoid the needless creation of tables for functions that don't need to return the results of the loop.
2990 1551
2991# Continue 1552# Continue
@@ -3000,18 +1561,6 @@ while i < 10
3000 print i 1561 print i
3001``` 1562```
3002 1563
3003<YueDisplay>
3004
3005```yue
3006i = 0
3007while i < 10
3008 i += 1
3009 continue if i % 2 == 0
3010 print i
3011```
3012
3013</YueDisplay>
3014
3015continue can also be used with loop expressions to prevent that iteration from accumulating into the result. This examples filters the array table into just even numbers: 1564continue can also be used with loop expressions to prevent that iteration from accumulating into the result. This examples filters the array table into just even numbers:
3016 1565
3017```yuescript 1566```yuescript
@@ -3021,17 +1570,6 @@ odds = for x in *my_numbers
3021 x 1570 x
3022``` 1571```
3023 1572
3024<YueDisplay>
3025
3026```yue
3027my_numbers = [1, 2, 3, 4, 5, 6]
3028odds = for x in *my_numbers
3029 continue if x % 2 == 1
3030 x
3031```
3032
3033</YueDisplay>
3034
3035# Switch 1573# Switch
3036 1574
3037The 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. In switch statement, you can also use assignment expression to store temporary variable value. 1575The 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. In switch statement, you can also use assignment expression to store temporary variable value.
@@ -3046,20 +1584,6 @@ switch name := "Dan"
3046 print "I don't know about you with name #{name}" 1584 print "I don't know about you with name #{name}"
3047``` 1585```
3048 1586
3049<YueDisplay>
3050
3051```yue
3052switch name := "Dan"
3053 when "Robert"
3054 print "You are Robert"
3055 when "Dan", "Daniel"
3056 print "Your name, it's Dan"
3057 else
3058 print "I don't know about you with name #{name}"
3059```
3060
3061</YueDisplay>
3062
3063A switch when clause can match against multiple values by listing them out comma separated. 1587A switch when clause can match against multiple values by listing them out comma separated.
3064 1588
3065Switches can be used as expressions as well, here we can assign the result of the switch to a variable: 1589Switches can be used as expressions as well, here we can assign the result of the switch to a variable:
@@ -3075,21 +1599,6 @@ next_number = switch b
3075 error "can't count that high!" 1599 error "can't count that high!"
3076``` 1600```
3077 1601
3078<YueDisplay>
3079
3080```yue
3081b = 1
3082next_number = switch b
3083 when 1
3084 2
3085 when 2
3086 3
3087 else
3088 error "can't count that high!"
3089```
3090
3091</YueDisplay>
3092
3093We 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. 1602We 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.
3094 1603
3095```yuescript 1604```yuescript
@@ -3099,17 +1608,6 @@ msg = switch math.random(1, 5)
3099 else "not so lucky" 1608 else "not so lucky"
3100``` 1609```
3101 1610
3102<YueDisplay>
3103
3104```yue
3105msg = switch math.random(1, 5)
3106 when 1 then "you are lucky"
3107 when 2 then "you are almost lucky"
3108 else "not so lucky"
3109```
3110
3111</YueDisplay>
3112
3113If you want to write code with one less indent when writing a switch statement, you can put the first when clause on the statement start line, and then all other clauses can be written with one less indent. 1611If you want to write code with one less indent when writing a switch statement, you can put the first when clause on the statement start line, and then all other clauses can be written with one less indent.
3114 1612
3115```yuescript 1613```yuescript
@@ -3125,23 +1623,6 @@ else
3125 print "not so lucky" 1623 print "not so lucky"
3126``` 1624```
3127 1625
3128<YueDisplay>
3129
3130```yue
3131switch math.random(1, 5)
3132 when 1
3133 print "you are lucky" -- two indents
3134 else
3135 print "not so lucky"
3136
3137switch math.random(1, 5) when 1
3138 print "you are lucky" -- one indent
3139else
3140 print "not so lucky"
3141```
3142
3143</YueDisplay>
3144
3145It 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. 1626It 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.
3146 1627
3147## Table Matching 1628## Table Matching
@@ -3163,25 +1644,6 @@ for item in *items
3163 print "size #{width}, #{height}" 1644 print "size #{width}, #{height}"
3164``` 1645```
3165 1646
3166<YueDisplay>
3167
3168```yue
3169items =
3170 * x: 100
3171 y: 200
3172 * width: 300
3173 height: 400
3174
3175for item in *items
3176 switch item
3177 when :x, :y
3178 print "Vec2 #{x}, #{y}"
3179 when :width, :height
3180 print "size #{width}, #{height}"
3181```
3182
3183</YueDisplay>
3184
3185You can use default values to optionally destructure the table for some fields. 1647You can use default values to optionally destructure the table for some fields.
3186 1648
3187```yuescript 1649```yuescript
@@ -3194,20 +1656,6 @@ switch item
3194 print "Vec2 #{x}, #{y}" -- table destructuring will still pass 1656 print "Vec2 #{x}, #{y}" -- table destructuring will still pass
3195``` 1657```
3196 1658
3197<YueDisplay>
3198
3199```yue
3200item = {}
3201
3202{pos: {:x = 50, :y = 200}} = item -- get error: attempt to index a nil value (field 'pos')
3203
3204switch item
3205 when {pos: {:x = 50, :y = 200}}
3206 print "Vec2 #{x}, #{y}" -- table destructuring will still pass
3207```
3208
3209</YueDisplay>
3210
3211You can also match against array elements, table fields, and even nested structures with array or table literals. 1659You can also match against array elements, table fields, and even nested structures with array or table literals.
3212 1660
3213Match against array elements. 1661Match against array elements.
@@ -3222,20 +1670,6 @@ switch tb
3222 print "1, 2, #{b}" 1670 print "1, 2, #{b}"
3223``` 1671```
3224 1672
3225<YueDisplay>
3226
3227```yue
3228switch tb
3229 when [1, 2, 3]
3230 print "1, 2, 3"
3231 when [1, b, 3]
3232 print "1, #{b}, 3"
3233 when [1, 2, b = 3] -- b has a default value
3234 print "1, 2, #{b}"
3235```
3236
3237</YueDisplay>
3238
3239Match against table fields with destructuring. 1673Match against table fields with destructuring.
3240 1674
3241```yuescript 1675```yuescript
@@ -3248,20 +1682,6 @@ switch tb
3248 print "invalid" 1682 print "invalid"
3249``` 1683```
3250 1684
3251<YueDisplay>
3252
3253```yue
3254switch tb
3255 when success: true, :result
3256 print "success", result
3257 when success: false
3258 print "failed", result
3259 else
3260 print "invalid"
3261```
3262
3263</YueDisplay>
3264
3265Match against nested table structures. 1685Match against nested table structures.
3266 1686
3267```yuescript 1687```yuescript
@@ -3274,20 +1694,6 @@ switch tb
3274 print "invalid" 1694 print "invalid"
3275``` 1695```
3276 1696
3277<YueDisplay>
3278
3279```yue
3280switch tb
3281 when data: {type: "success", :content}
3282 print "success", content
3283 when data: {type: "error", :content}
3284 print "failed", content
3285 else
3286 print "invalid"
3287```
3288
3289</YueDisplay>
3290
3291Match against array of tables. 1697Match against array of tables.
3292 1698
3293```yuescript 1699```yuescript
@@ -3301,21 +1707,6 @@ switch tb
3301 print "matched", fourth 1707 print "matched", fourth
3302``` 1708```
3303 1709
3304<YueDisplay>
3305
3306```yue
3307switch tb
3308 when [
3309 {a: 1, b: 2}
3310 {a: 3, b: 4}
3311 {a: 5, b: 6}
3312 fourth
3313 ]
3314 print "matched", fourth
3315```
3316
3317</YueDisplay>
3318
3319Match against a list and capture a range of elements. 1710Match against a list and capture a range of elements.
3320 1711
3321```yuescript 1712```yuescript
@@ -3327,19 +1718,6 @@ switch segments
3327 print "Action:", action -- prints: "view" 1718 print "Action:", action -- prints: "view"
3328``` 1719```
3329 1720
3330<YueDisplay>
3331
3332```yue
3333segments = ["admin", "users", "logs", "view"]
3334switch segments
3335 when [...groups, resource, action]
3336 print "Group:", groups -- prints: {"admin", "users"}
3337 print "Resource:", resource -- prints: "logs"
3338 print "Action:", action -- prints: "view"
3339```
3340
3341</YueDisplay>
3342
3343# While Loop 1721# While Loop
3344 1722
3345The while loop also comes in four variations: 1723The while loop also comes in four variations:
@@ -3353,19 +1731,6 @@ while i > 0
3353while running == true do my_function! 1731while running == true do my_function!
3354``` 1732```
3355 1733
3356<YueDisplay>
3357
3358```yue
3359i = 10
3360while i > 0
3361 print i
3362 i -= 1
3363
3364while running == true do my_function!
3365```
3366
3367</YueDisplay>
3368
3369```yuescript 1734```yuescript
3370i = 10 1735i = 10
3371until i == 0 1736until i == 0
@@ -3375,18 +1740,6 @@ until i == 0
3375until running == false do my_function! 1740until running == false do my_function!
3376``` 1741```
3377 1742
3378<YueDisplay>
3379
3380```yue
3381i = 10
3382until i == 0
3383 print i
3384 i -= 1
3385until running == false do my_function!
3386```
3387
3388</YueDisplay>
3389
3390Like for loops, the while loop can also be used as an expression. While and until loop expressions support `break` with multiple return values. 1743Like for loops, the while loop can also be used as an expression. While and until loop expressions support `break` with multiple return values.
3391 1744
3392```yuescript 1745```yuescript
@@ -3395,16 +1748,6 @@ value, doubled = while true
3395 break n, n * 2 if n > 10 1748 break n, n * 2 if n > 10
3396``` 1749```
3397 1750
3398<YueDisplay>
3399
3400```yue
3401value, doubled = while true
3402 n = get_next!
3403 break n, n * 2 if n > 10
3404```
3405
3406</YueDisplay>
3407
3408Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned. 1751Additionally, for a function to return the accumulated value of a while loop, the statement must be explicitly returned.
3409 1752
3410## Repeat Loop 1753## Repeat Loop
@@ -3419,18 +1762,6 @@ repeat
3419until i == 0 1762until i == 0
3420``` 1763```
3421 1764
3422<YueDisplay>
3423
3424```yue
3425i = 10
3426repeat
3427 print i
3428 i -= 1
3429until i == 0
3430```
3431
3432</YueDisplay>
3433
3434Repeat loop expressions also support `break` with multiple return values: 1765Repeat loop expressions also support `break` with multiple return values:
3435 1766
3436```yuescript 1767```yuescript
@@ -3441,18 +1772,6 @@ value, scaled = repeat
3441until false 1772until false
3442``` 1773```
3443 1774
3444<YueDisplay>
3445
3446```yue
3447i = 1
3448value, scaled = repeat
3449 break i, i * 100 if i > 3
3450 i += 1
3451until false
3452```
3453
3454</YueDisplay>
3455
3456# Function Stubs 1775# Function Stubs
3457 1776
3458It is common to pass a function from an object around as a value, for example, passing an instance method into a function as a callback. If the function expects the object it is operating on as the first argument then you must somehow bundle that object with the function so it can be called properly. 1777It is common to pass a function from an object around as a value, for example, passing an instance method into a function as a callback. If the function expects the object it is operating on as the first argument then you must somehow bundle that object with the function so it can be called properly.
@@ -3480,29 +1799,6 @@ run_callback my_object.write
3480run_callback my_object\write 1799run_callback my_object\write
3481``` 1800```
3482 1801
3483<YueDisplay>
3484
3485```yue
3486my_object = {
3487 value: 1000
3488 write: => print "the value:", @value
3489}
3490
3491run_callback = (func) ->
3492 print "running callback..."
3493 func!
3494
3495-- this will not work:
3496-- the function has to no reference to my_object
3497run_callback my_object.write
3498
3499-- function stub syntax
3500-- lets us bundle the object into a new function
3501run_callback my_object\write
3502```
3503
3504</YueDisplay>
3505
3506# Backcalls 1802# Backcalls
3507 1803
3508Backcalls are used for unnesting callbacks. They are defined using arrows pointed to the left as the last parameter by default filling in a function call. All the syntax is mostly the same as regular arrow functions except that it is just pointing the other way and the function body does not require indent. 1804Backcalls are used for unnesting callbacks. They are defined using arrows pointed to the left as the last parameter by default filling in a function call. All the syntax is mostly the same as regular arrow functions except that it is just pointing the other way and the function body does not require indent.
@@ -3512,15 +1808,6 @@ x <- f
3512print "hello" .. x 1808print "hello" .. x
3513``` 1809```
3514 1810
3515<YueDisplay>
3516
3517```yue
3518x <- f
3519print "hello" .. x
3520```
3521
3522</YueDisplay>
3523
3524Fat arrow functions are also available. 1811Fat arrow functions are also available.
3525 1812
3526```yuescript 1813```yuescript
@@ -3528,15 +1815,6 @@ Fat arrow functions are also available.
3528print @value 1815print @value
3529``` 1816```
3530 1817
3531<YueDisplay>
3532
3533```yue
3534<= f
3535print @value
3536```
3537
3538</YueDisplay>
3539
3540You can specify a placeholder for where you want the backcall function to go as a parameter. 1818You can specify a placeholder for where you want the backcall function to go as a parameter.
3541 1819
3542```yuescript 1820```yuescript
@@ -3544,15 +1822,6 @@ You can specify a placeholder for where you want the backcall function to go as
3544x * 2 1822x * 2
3545``` 1823```
3546 1824
3547<YueDisplay>
3548
3549```yue
3550(x) <- map _, [1, 2, 3]
3551x * 2
3552```
3553
3554</YueDisplay>
3555
3556If you wish to have further code after your backcalls, you can set them aside with a do statement. And the parentheses can be omitted with non-fat arrow functions. 1825If you wish to have further code after your backcalls, you can set them aside with a do statement. And the parentheses can be omitted with non-fat arrow functions.
3557 1826
3558```yuescript 1827```yuescript
@@ -3564,19 +1833,6 @@ result, msg = do
3564print result, msg 1833print result, msg
3565``` 1834```
3566 1835
3567<YueDisplay>
3568
3569```yue
3570result, msg = do
3571 data <- readAsync "filename.txt"
3572 print data
3573 info <- processAsync data
3574 check info
3575print result, msg
3576```
3577
3578</YueDisplay>
3579
3580# Function Literals 1836# Function Literals
3581 1837
3582All functions are created using a function expression. A simple function is denoted using the arrow: **->**. 1838All functions are created using a function expression. A simple function is denoted using the arrow: **->**.
@@ -3586,15 +1842,6 @@ my_function = ->
3586my_function() -- call the empty function 1842my_function() -- call the empty function
3587``` 1843```
3588 1844
3589<YueDisplay>
3590
3591```yue
3592my_function = ->
3593my_function() -- call the empty function
3594```
3595
3596</YueDisplay>
3597
3598The 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: 1845The 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:
3599 1846
3600```yuescript 1847```yuescript
@@ -3605,18 +1852,6 @@ func_b = ->
3605 print "The value:", value 1852 print "The value:", value
3606``` 1853```
3607 1854
3608<YueDisplay>
3609
3610```yue
3611func_a = -> print "hello world"
3612
3613func_b = ->
3614 value = 100
3615 print "The value:", value
3616```
3617
3618</YueDisplay>
3619
3620If 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. 1855If 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.
3621 1856
3622```yuescript 1857```yuescript
@@ -3624,29 +1859,12 @@ func_a!
3624func_b() 1859func_b()
3625``` 1860```
3626 1861
3627<YueDisplay>
3628
3629```yue
3630func_a!
3631func_b()
3632```
3633
3634</YueDisplay>
3635
3636Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses: 1862Functions with arguments can be created by preceding the arrow with a list of argument names in parentheses:
3637 1863
3638```yuescript 1864```yuescript
3639sum = (x, y) -> print "sum", x + y 1865sum = (x, y) -> print "sum", x + y
3640``` 1866```
3641 1867
3642<YueDisplay>
3643
3644```yue
3645sum = (x, y) -> print "sum", x + y
3646```
3647
3648</YueDisplay>
3649
3650Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left. 1868Functions can be called by listing the arguments after the name of an expression that evaluates to a function. When chaining together function calls, the arguments are applied to the closest function to the left.
3651 1869
3652```yuescript 1870```yuescript
@@ -3656,31 +1874,12 @@ print sum 10, 20
3656a b c "a", "b", "c" 1874a b c "a", "b", "c"
3657``` 1875```
3658 1876
3659<YueDisplay>
3660
3661```yue
3662sum 10, 20
3663print sum 10, 20
3664
3665a b c "a", "b", "c"
3666```
3667
3668</YueDisplay>
3669
3670In 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. 1877In 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.
3671 1878
3672```yuescript 1879```yuescript
3673print "x:", sum(10, 20), "y:", sum(30, 40) 1880print "x:", sum(10, 20), "y:", sum(30, 40)
3674``` 1881```
3675 1882
3676<YueDisplay>
3677
3678```yue
3679print "x:", sum(10, 20), "y:", sum(30, 40)
3680```
3681
3682</YueDisplay>
3683
3684There must not be any space between the opening parenthesis and the function. 1883There must not be any space between the opening parenthesis and the function.
3685 1884
3686Functions will coerce the last statement in their body into a return statement, this is called implicit return: 1885Functions will coerce the last statement in their body into a return statement, this is called implicit return:
@@ -3690,29 +1889,12 @@ sum = (x, y) -> x + y
3690print "The sum is ", sum 10, 20 1889print "The sum is ", sum 10, 20
3691``` 1890```
3692 1891
3693<YueDisplay>
3694
3695```yue
3696sum = (x, y) -> x + y
3697print "The sum is ", sum 10, 20
3698```
3699
3700</YueDisplay>
3701
3702And if you need to explicitly return, you can use the return keyword: 1892And if you need to explicitly return, you can use the return keyword:
3703 1893
3704```yuescript 1894```yuescript
3705sum = (x, y) -> return x + y 1895sum = (x, y) -> return x + y
3706``` 1896```
3707 1897
3708<YueDisplay>
3709
3710```yue
3711sum = (x, y) -> return x + y
3712```
3713
3714</YueDisplay>
3715
3716Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas: 1898Just like in Lua, functions can return multiple values. The last statement must be a list of values separated by commas:
3717 1899
3718```yuescript 1900```yuescript
@@ -3720,15 +1902,6 @@ mystery = (x, y) -> x + y, x - y
3720a, b = mystery 10, 20 1902a, b = mystery 10, 20
3721``` 1903```
3722 1904
3723<YueDisplay>
3724
3725```yue
3726mystery = (x, y) -> x + y, x - y
3727a, b = mystery 10, 20
3728```
3729
3730</YueDisplay>
3731
3732## Fat Arrows 1905## Fat Arrows
3733 1906
3734Because it is an idiom in Lua to send an object as the first argument when calling a method, a special syntax is provided for creating functions which automatically includes a self argument. 1907Because it is an idiom in Lua to send an object as the first argument when calling a method, a special syntax is provided for creating functions which automatically includes a self argument.
@@ -3737,14 +1910,6 @@ Because it is an idiom in Lua to send an object as the first argument when calli
3737func = (num) => @value + num 1910func = (num) => @value + num
3738``` 1911```
3739 1912
3740<YueDisplay>
3741
3742```yue
3743func = (num) => @value + num
3744```
3745
3746</YueDisplay>
3747
3748## Argument Defaults 1913## Argument Defaults
3749 1914
3750It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run. 1915It is possible to provide default values for the arguments of a function. An argument is determined to be empty if its value is nil. Any nil arguments that have a default value will be replace before the body of the function is run.
@@ -3755,16 +1920,6 @@ my_function = (name = "something", height = 100) ->
3755 print "My height is", height 1920 print "My height is", height
3756``` 1921```
3757 1922
3758<YueDisplay>
3759
3760```yue
3761my_function = (name = "something", height = 100) ->
3762 print "Hello I am", name
3763 print "My height is", height
3764```
3765
3766</YueDisplay>
3767
3768An 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. 1923An 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.
3769 1924
3770```yuescript 1925```yuescript
@@ -3772,15 +1927,6 @@ some_args = (x = 100, y = x + 1000) ->
3772 print x + y 1927 print x + y
3773``` 1928```
3774 1929
3775<YueDisplay>
3776
3777```yue
3778some_args = (x = 100, y = x + 1000) ->
3779 print x + y
3780```
3781
3782</YueDisplay>
3783
3784## Considerations 1930## Considerations
3785 1931
3786Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace. 1932Because of the expressive parentheses-less way of calling functions, some restrictions must be put in place to avoid parsing ambiguity involving whitespace.
@@ -3794,17 +1940,6 @@ c = x -y
3794d = x- z 1940d = x- z
3795``` 1941```
3796 1942
3797<YueDisplay>
3798
3799```yue
3800a = x - 10
3801b = x-10
3802c = x -y
3803d = x- z
3804```
3805
3806</YueDisplay>
3807
3808The precedence of the first argument of a function call can be controlled using whitespace if the argument is a literal string. In Lua, it is common to leave off parentheses when calling a function with a single string or table literal. 1943The precedence of the first argument of a function call can be controlled using whitespace if the argument is a literal string. In Lua, it is common to leave off parentheses when calling a function with a single string or table literal.
3809 1944
3810When there is no space between a variable and a string literal, the function call takes precedence over any following expressions. No other arguments can be passed to the function when it is called this way. 1945When there is no space between a variable and a string literal, the function call takes precedence over any following expressions. No other arguments can be passed to the function when it is called this way.
@@ -3816,15 +1951,6 @@ x = func"hello" + 100
3816y = func "hello" + 100 1951y = func "hello" + 100
3817``` 1952```
3818 1953
3819<YueDisplay>
3820
3821```yue
3822x = func"hello" + 100
3823y = func "hello" + 100
3824```
3825
3826</YueDisplay>
3827
3828## Multi-line arguments 1954## Multi-line arguments
3829 1955
3830When calling functions that take a large number of arguments, it is convenient to split the argument list over multiple lines. Because of the white-space sensitive nature of the language, care must be taken when splitting up the argument list. 1956When calling functions that take a large number of arguments, it is convenient to split the argument list over multiple lines. Because of the white-space sensitive nature of the language, care must be taken when splitting up the argument list.
@@ -3841,20 +1967,6 @@ cool_func 1, 2,
3841 7, 8 1967 7, 8
3842``` 1968```
3843 1969
3844<YueDisplay>
3845
3846```yue
3847my_func 5, 4, 3,
3848 8, 9, 10
3849
3850cool_func 1, 2,
3851 3, 4,
3852 5, 6,
3853 7, 8
3854```
3855
3856</YueDisplay>
3857
3858This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to. 1970This type of invocation can be nested. The level of indentation is used to determine to which function the arguments belong to.
3859 1971
3860```yuescript 1972```yuescript
@@ -3864,17 +1976,6 @@ my_func 5, 6, 7,
3864 5, 4 1976 5, 4
3865``` 1977```
3866 1978
3867<YueDisplay>
3868
3869```yue
3870my_func 5, 6, 7,
3871 6, another_func 6, 7, 8,
3872 9, 1, 2,
3873 5, 4
3874```
3875
3876</YueDisplay>
3877
3878Because 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. 1979Because 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.
3879 1980
3880```yuescript 1981```yuescript
@@ -3885,18 +1986,6 @@ x = [
3885] 1986]
3886``` 1987```
3887 1988
3888<YueDisplay>
3889
3890```yue
3891x = [
3892 1, 2, 3, 4, a_func 4, 5,
3893 5, 6,
3894 8, 9, 10
3895]
3896```
3897
3898</YueDisplay>
3899
3900Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on. 1989Although uncommon, notice how we can give a deeper indentation for function arguments if we know we will be using a lower indentation further on.
3901 1990
3902```yuescript 1991```yuescript
@@ -3906,17 +1995,6 @@ y = [ my_func 1, 2, 3,
3906] 1995]
3907``` 1996```
3908 1997
3909<YueDisplay>
3910
3911```yue
3912y = [ my_func 1, 2, 3,
3913 4, 5,
3914 5, 6, 7
3915]
3916```
3917
3918</YueDisplay>
3919
3920The 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: 1998The 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:
3921 1999
3922```yuescript 2000```yuescript
@@ -3933,24 +2011,6 @@ if func 1, 2, 3,
3933 print "I am inside if" 2011 print "I am inside if"
3934``` 2012```
3935 2013
3936<YueDisplay>
3937
3938```yue
3939if func 1, 2, 3,
3940 "hello",
3941 "world"
3942 print "hello"
3943 print "I am inside if"
3944
3945if func 1, 2, 3,
3946 "hello",
3947 "world"
3948 print "hello"
3949 print "I am inside if"
3950```
3951
3952</YueDisplay>
3953
3954## Parameter Destructuring 2014## Parameter Destructuring
3955 2015
3956YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available: 2016YueScript now supports destructuring function parameters when the argument is an object. Two forms of destructuring table literals are available:
@@ -3972,23 +2032,6 @@ arg1 = {a: 0}
3972f2 arg1, arg2 2032f2 arg1, arg2
3973``` 2033```
3974 2034
3975<YueDisplay>
3976
3977```yue
3978f1 = (:a, :b, :c) ->
3979 print a, b, c
3980
3981f1 a: 1, b: "2", c: {}
3982
3983f2 = ({a: a1 = 123, :b = 'abc'}, c = {}) ->
3984print a1, b, c
3985
3986arg1 = {a: 0}
3987f2 arg1, arg2
3988```
3989
3990</YueDisplay>
3991
3992## Prefixed Return Expression 2035## Prefixed Return Expression
3993 2036
3994When working with deeply nested function bodies, it can be tedious to maintain readability and consistency of the return value. To address this, YueScript introduces the **Prefixed Return Expression** syntax. Its form is as follows: 2037When working with deeply nested function bodies, it can be tedious to maintain readability and consistency of the return value. To address this, YueScript introduces the **Prefixed Return Expression** syntax. Its form is as follows:
@@ -4002,19 +2045,6 @@ findFirstEven = (list): nil ->
4002 return sub 2045 return sub
4003``` 2046```
4004 2047
4005<YueDisplay>
4006
4007```yue
4008findFirstEven = (list): nil ->
4009 for item in *list
4010 if type(item) == "table"
4011 for sub in *item
4012 if sub % 2 == 0
4013 return sub
4014```
4015
4016</YueDisplay>
4017
4018This is equivalent to: 2048This is equivalent to:
4019 2049
4020```yuescript 2050```yuescript
@@ -4027,20 +2057,6 @@ findFirstEven = (list) ->
4027 nil 2057 nil
4028``` 2058```
4029 2059
4030<YueDisplay>
4031
4032```yue
4033findFirstEven = (list) ->
4034 for item in *list
4035 if type(item) == "table"
4036 for sub in *item
4037 if sub % 2 == 0
4038 return sub
4039 nil
4040```
4041
4042</YueDisplay>
4043
4044The only difference is that you can move the final return expression before the `->` or `=>` token to indicate the function’s implicit return value as the last statement. This way, even in functions with multiple nested loops or conditional branches, you no longer need to write a trailing return expression at the end of the function body, making the logic structure more straightforward and easier to follow. 2060The only difference is that you can move the final return expression before the `->` or `=>` token to indicate the function’s implicit return value as the last statement. This way, even in functions with multiple nested loops or conditional branches, you no longer need to write a trailing return expression at the end of the function body, making the logic structure more straightforward and easier to follow.
4045 2061
4046## Named Varargs 2062## Named Varargs
@@ -4069,32 +2085,6 @@ process = (...args) ->
4069process 1, nil, 3, nil, 5 2085process 1, nil, 3, nil, 5
4070``` 2086```
4071 2087
4072<YueDisplay>
4073
4074```yue
4075f = (...t) ->
4076 print "argument count:", t.n
4077 print "table length:", #t
4078 for i = 1, t.n
4079 print t[i]
4080
4081f 1, 2, 3
4082f "a", "b", "c", "d"
4083f!
4084
4085-- Handling cases with nil values
4086process = (...args) ->
4087 sum = 0
4088 for i = 1, args.n
4089 if args[i] != nil and type(args[i]) == "number"
4090 sum += args[i]
4091 sum
4092
4093process 1, nil, 3, nil, 5
4094```
4095
4096</YueDisplay>
4097
4098# Whitespace 2088# Whitespace
4099 2089
4100YueScript is a whitespace significant language. You have to write some code block in the same indent with space **' '** or tab **'\t'** like function body, value list and some control blocks. And expressions containing different whitespaces might mean different things. Tab is treated like 4 space, but it's better not mix the use of spaces and tabs. 2090YueScript is a whitespace significant language. You have to write some code block in the same indent with space **' '** or tab **'\t'** like function body, value list and some control blocks. And expressions containing different whitespaces might mean different things. Tab is treated like 4 space, but it's better not mix the use of spaces and tabs.
@@ -4107,14 +2097,6 @@ A statement normally ends at a line break. You can also use a semicolon `;` to e
4107a = 1; b = 2; print a + b 2097a = 1; b = 2; print a + b
4108``` 2098```
4109 2099
4110<YueDisplay>
4111
4112```yue
4113a = 1; b = 2; print a + b
4114```
4115
4116</YueDisplay>
4117
4118## Multiline Chaining 2100## Multiline Chaining
4119 2101
4120You can write multi-line chaining function calls with a same indent. 2102You can write multi-line chaining function calls with a same indent.
@@ -4128,19 +2110,6 @@ Rx.Observable
4128 \subscribe print 2110 \subscribe print
4129``` 2111```
4130 2112
4131<YueDisplay>
4132
4133```yue
4134Rx.Observable
4135 .fromRange 1, 8
4136 \filter (x) -> x % 2 == 0
4137 \concat Rx.Observable.of 'who do we appreciate'
4138 \map (value) -> value .. '!'
4139 \subscribe print
4140```
4141
4142</YueDisplay>
4143
4144# Comment 2113# Comment
4145 2114
4146```yuescript 2115```yuescript
@@ -4156,23 +2125,6 @@ It's OK.
4156func --[[port]] 3000, --[[ip]] "192.168.1.1" 2125func --[[port]] 3000, --[[ip]] "192.168.1.1"
4157``` 2126```
4158 2127
4159<YueDisplay>
4160
4161```yue
4162-- I am a comment
4163
4164str = --[[
4165This is a multi-line comment.
4166It's OK.
4167]] strA \ -- comment 1
4168 .. strB \ -- comment 2
4169 .. strC
4170
4171func --[[port]] 3000, --[[ip]] "192.168.1.1"
4172```
4173
4174</YueDisplay>
4175
4176# Attributes 2128# Attributes
4177 2129
4178Syntax support for Lua 5.4 attributes. And you can still use both the `const` and `close` declaration and get constant check and scoped callback working when targeting Lua versions below 5.4. 2130Syntax support for Lua 5.4 attributes. And you can still use both the `const` and `close` declaration and get constant check and scoped callback working when targeting Lua versions below 5.4.
@@ -4182,15 +2134,6 @@ const a = 123
4182close _ = <close>: -> print "Out of scope." 2134close _ = <close>: -> print "Out of scope."
4183``` 2135```
4184 2136
4185<YueDisplay>
4186
4187```yue
4188const a = 123
4189close _ = <close>: -> print "Out of scope."
4190```
4191
4192</YueDisplay>
4193
4194You can do desctructuring with variables attributed as constant. 2137You can do desctructuring with variables attributed as constant.
4195 2138
4196```yuescript 2139```yuescript
@@ -4198,15 +2141,6 @@ const {:a, :b, c, d} = tb
4198-- a = 1 2141-- a = 1
4199``` 2142```
4200 2143
4201<YueDisplay>
4202
4203```yue
4204const {:a, :b, c, d} = tb
4205-- a = 1
4206```
4207
4208</YueDisplay>
4209
4210You can also declare a global variable to be `const`. 2144You can also declare a global variable to be `const`.
4211 2145
4212```yuescript 2146```yuescript
@@ -4214,15 +2148,6 @@ global const Constant = 123
4214-- Constant = 1 2148-- Constant = 1
4215``` 2149```
4216 2150
4217<YueDisplay>
4218
4219```yue
4220global const Constant = 123
4221-- Constant = 1
4222```
4223
4224</YueDisplay>
4225
4226# Operator 2151# Operator
4227 2152
4228All of Lua's binary and unary operators are available. Additionally **!=** is as an alias for **~=**, and either **\\** or **::** can be used to write a chaining function call like `tb\func!` or `tb::func!`. And Yuescipt offers some other special operators to write more expressive codes. 2153All of Lua's binary and unary operators are available. Additionally **!=** is as an alias for **~=**, and either **\\** or **::** can be used to write a chaining function call like `tb\func!` or `tb::func!`. And Yuescipt offers some other special operators to write more expressive codes.
@@ -4232,15 +2157,6 @@ tb\func! if tb ~= nil
4232tb::func! if tb != nil 2157tb::func! if tb != nil
4233``` 2158```
4234 2159
4235<YueDisplay>
4236
4237```yue
4238tb\func! if tb ~= nil
4239tb::func! if tb != nil
4240```
4241
4242</YueDisplay>
4243
4244## Chaining Comparisons 2160## Chaining Comparisons
4245 2161
4246Comparisons can be arbitrarily chained: 2162Comparisons can be arbitrarily chained:
@@ -4254,19 +2170,6 @@ print 1 <= a <= 10
4254-- output: true 2170-- output: true
4255``` 2171```
4256 2172
4257<YueDisplay>
4258
4259```yue
4260print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
4261-- output: true
4262
4263a = 5
4264print 1 <= a <= 10
4265-- output: true
4266```
4267
4268</YueDisplay>
4269
4270Note the evaluation behavior of chained comparisons: 2173Note the evaluation behavior of chained comparisons:
4271 2174
4272```yuescript 2175```yuescript
@@ -4292,33 +2195,6 @@ print v(1) > v(2) <= v(3)
4292]] 2195]]
4293``` 2196```
4294 2197
4295<YueDisplay>
4296
4297```yue
4298v = (x) ->
4299 print x
4300 x
4301
4302print v(1) < v(2) <= v(3)
4303--[[
4304 output:
4305 2
4306 1
4307 3
4308 true
4309]]
4310
4311print v(1) > v(2) <= v(3)
4312--[[
4313 output:
4314 2
4315 1
4316 false
4317]]
4318```
4319
4320</YueDisplay>
4321
4322The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) and v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `and` operator should be used explicitly. 2198The middle expression is only evaluated once, rather than twice as it would be if the expression were written as `v(1) < v(2) and v(2) <= v(3)`. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit `and` operator should be used explicitly.
4323 2199
4324## Table Appending 2200## Table Appending
@@ -4330,15 +2206,6 @@ tab = []
4330tab[] = "Value" 2206tab[] = "Value"
4331``` 2207```
4332 2208
4333<YueDisplay>
4334
4335```yue
4336tab = []
4337tab[] = "Value"
4338```
4339
4340</YueDisplay>
4341
4342You can also use the spread operator `...` to append all elements from one list to another: 2209You can also use the spread operator `...` to append all elements from one list to another:
4343 2210
4344```yuescript 2211```yuescript
@@ -4348,17 +2215,6 @@ tbA[] = ...tbB
4348-- tbA is now [1, 2, 3, 4, 5, 6] 2215-- tbA is now [1, 2, 3, 4, 5, 6]
4349``` 2216```
4350 2217
4351<YueDisplay>
4352
4353```yue
4354tbA = [1, 2, 3]
4355tbB = [4, 5, 6]
4356tbA[] = ...tbB
4357-- tbA is now [1, 2, 3, 4, 5, 6]
4358```
4359
4360</YueDisplay>
4361
4362## Table Spreading 2218## Table Spreading
4363 2219
4364You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals. 2220You can concatenate array tables or hash tables using spread operator `...` before expressions in table literals.
@@ -4380,27 +2236,6 @@ b = {4, 5, y: 1}
4380merge = {...a, ...b} 2236merge = {...a, ...b}
4381``` 2237```
4382 2238
4383<YueDisplay>
4384
4385```yue
4386parts =
4387 * "shoulders"
4388 * "knees"
4389lyrics =
4390 * "head"
4391 * ...parts
4392 * "and"
4393 * "toes"
4394
4395copy = {...other}
4396
4397a = {1, 2, 3, x: 1}
4398b = {4, 5, y: 1}
4399merge = {...a, ...b}
4400```
4401
4402</YueDisplay>
4403
4404## Table Reversed Indexing 2239## Table Reversed Indexing
4405 2240
4406You can use the **#** operator to get the last elements of a table. 2241You can use the **#** operator to get the last elements of a table.
@@ -4411,16 +2246,6 @@ second_last = data.items[#-1]
4411data.items[#] = 1 2246data.items[#] = 1
4412``` 2247```
4413 2248
4414<YueDisplay>
4415
4416```yue
4417last = data.items[#]
4418second_last = data.items[#-1]
4419data.items[#] = 1
4420```
4421
4422</YueDisplay>
4423
4424## Metatable 2249## Metatable
4425 2250
4426The **<>** operator can be used as a shortcut for metatable manipulation. 2251The **<>** operator can be used as a shortcut for metatable manipulation.
@@ -4445,26 +2270,6 @@ print d.value
4445close _ = <close>: -> print "out of scope" 2270close _ = <close>: -> print "out of scope"
4446``` 2271```
4447 2272
4448<YueDisplay>
4449
4450```yue
4451mt = {}
4452add = (right) => <>: mt, value: @value + right.value
4453mt.__add = add
4454
4455a = <>: mt, value: 1
4456 -- set field with variable of the same name
4457b = :<add>, value: 2
4458c = <add>: mt.__add, value: 3
4459
4460d = a + b + c
4461print d.value
4462
4463close _ = <close>: -> print "out of scope"
4464```
4465
4466</YueDisplay>
4467
4468### Metatable Accessing 2273### Metatable Accessing
4469 2274
4470Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**. 2275Accessing metatable with **<>** or metamethod name surrounded by **<>** or writing some expression in **<>**.
@@ -4479,19 +2284,6 @@ tb.<> = __index: {item: "hello"}
4479print tb.item 2284print tb.item
4480``` 2285```
4481 2286
4482<YueDisplay>
4483
4484```yue
4485-- create with metatable containing field "value"
4486tb = <"value">: 123
4487tb.<index> = tb.<>
4488print tb.value
4489tb.<> = __index: {item: "hello"}
4490print tb.item
4491```
4492
4493</YueDisplay>
4494
4495### Metatable Destructure 2287### Metatable Destructure
4496 2288
4497Destruct metatable with metamethod key surrounded by **<>**. 2289Destruct metatable with metamethod key surrounded by **<>**.
@@ -4501,15 +2293,6 @@ Destruct metatable with metamethod key surrounded by **<>**.
4501print item, new, close, getter 2293print item, new, close, getter
4502``` 2294```
4503 2295
4504<YueDisplay>
4505
4506```yue
4507{item, :new, :<close>, <index>: getter} = tb
4508print item, new, close, getter
4509```
4510
4511</YueDisplay>
4512
4513## Existence 2296## Existence
4514 2297
4515The **?** operator can be used in a variety of contexts to check for existence. 2298The **?** operator can be used in a variety of contexts to check for existence.
@@ -4529,25 +2312,6 @@ with? io.open "test.txt", "w"
4529 \close! 2312 \close!
4530``` 2313```
4531 2314
4532<YueDisplay>
4533
4534```yue
4535func?!
4536print abc?["hello world"]?.xyz
4537
4538x = tab?.value
4539len = utf8?.len or string?.len or (o) -> #o
4540
4541if print and x?
4542 print x
4543
4544with? io.open "test.txt", "w"
4545 \write "hello"
4546 \close!
4547```
4548
4549</YueDisplay>
4550
4551## Piping 2315## Piping
4552 2316
4553Instead of a series of nested function calls, you can pipe values with operator **|>**. 2317Instead of a series of nested function calls, you can pipe values with operator **|>**.
@@ -4566,24 +2330,6 @@ readFile "example.txt"
4566 |> print 2330 |> print
4567``` 2331```
4568 2332
4569<YueDisplay>
4570
4571```yue
4572"hello" |> print
45731 |> print 2 -- insert pipe item as the first argument
45742 |> print 1, _, 3 -- pipe with a placeholder
4575
4576-- pipe expression in multiline
4577readFile "example.txt"
4578 |> extract language, {}
4579 |> parse language
4580 |> emit
4581 |> render
4582 |> print
4583```
4584
4585</YueDisplay>
4586
4587## Nil Coalescing 2333## Nil Coalescing
4588 2334
4589The nil-coalescing operator **??** returns the value of its left-hand operand if it isn't **nil**; otherwise, it evaluates the right-hand operand and returns its result. The **??** operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-nil. 2335The nil-coalescing operator **??** returns the value of its left-hand operand if it isn't **nil**; otherwise, it evaluates the right-hand operand and returns its result. The **??** operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-nil.
@@ -4596,17 +2342,6 @@ func a ?? {}
4596a ??= false 2342a ??= false
4597``` 2343```
4598 2344
4599<YueDisplay>
4600
4601```yue
4602local a, b, c, d
4603a = b ?? c ?? d
4604func a ?? {}
4605a ??= false
4606```
4607
4608</YueDisplay>
4609
4610## Implicit Object 2345## Implicit Object
4611 2346
4612You can write a list of implicit structures that starts with the symbol **\*** or **-** inside a table block. If you are creating implicit object, the fields of the object must be with the same indent. 2347You can write a list of implicit structures that starts with the symbol **\*** or **-** inside a table block. If you are creating implicit object, the fields of the object must be with the same indent.
@@ -4654,52 +2389,6 @@ tb =
4654 2389
4655``` 2390```
4656 2391
4657<YueDisplay>
4658
4659```yue
4660-- assignment with implicit object
4661list =
4662 * 1
4663 * 2
4664 * 3
4665
4666-- function call with implicit object
4667func
4668 * 1
4669 * 2
4670 * 3
4671
4672-- return with implicit object
4673f = ->
4674 return
4675 * 1
4676 * 2
4677 * 3
4678
4679-- table with implicit object
4680tb =
4681 name: "abc"
4682
4683 values:
4684 - "a"
4685 - "b"
4686 - "c"
4687
4688 objects:
4689 - name: "a"
4690 value: 1
4691 func: => @value + 1
4692 tb:
4693 fieldA: 1
4694
4695 - name: "b"
4696 value: 2
4697 func: => @value + 2
4698 tb: { }
4699```
4700
4701</YueDisplay>
4702
4703# Literals 2392# Literals
4704 2393
4705All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**. 2394All of the primitive literals in Lua can be used. This applies to numbers, strings, booleans, and **nil**.
@@ -4715,19 +2404,6 @@ some_string = "Here is a string
4715print "I am #{math.random! * 100}% sure." 2404print "I am #{math.random! * 100}% sure."
4716``` 2405```
4717 2406
4718<YueDisplay>
4719
4720```yue
4721some_string = "Here is a string
4722 that has a line break in it."
4723
4724-- You can mix expressions into string literals using #{} syntax.
4725-- String interpolation is only available in double quoted strings.
4726print "I am #{math.random! * 100}% sure."
4727```
4728
4729</YueDisplay>
4730
4731## Number Literals 2407## Number Literals
4732 2408
4733You can use underscores in a number literal to increase readability. 2409You can use underscores in a number literal to increase readability.
@@ -4738,16 +2414,6 @@ hex = 0xEF_BB_BF
4738binary = 0B10011 2414binary = 0B10011
4739``` 2415```
4740 2416
4741<YueDisplay>
4742
4743```yue
4744integer = 1_000_000
4745hex = 0xEF_BB_BF
4746binary = 0B10011
4747```
4748
4749</YueDisplay>
4750
4751## YAML Multiline String 2417## YAML Multiline String
4752 2418
4753The `|` prefix introduces a YAML-style multiline string literal: 2419The `|` prefix introduces a YAML-style multiline string literal:
@@ -4760,18 +2426,6 @@ str = |
4760 - #{expr} 2426 - #{expr}
4761``` 2427```
4762 2428
4763<YueDisplay>
4764
4765```yue
4766str = |
4767 key: value
4768 list:
4769 - item1
4770 - #{expr}
4771```
4772
4773</YueDisplay>
4774
4775This allows writing structured multiline text conveniently. All line breaks and indentation are preserved relative to the first non-empty line, and expressions inside `#{...}` are interpolated automatically as `tostring(expr)`. 2429This allows writing structured multiline text conveniently. All line breaks and indentation are preserved relative to the first non-empty line, and expressions inside `#{...}` are interpolated automatically as `tostring(expr)`.
4776 2430
4777YAML Multiline String automatically detects the common leading whitespace prefix (minimum indentation across all non-empty lines) and removes it from all lines. This makes it easy to indent your code visually without affecting the resulting string content. 2431YAML Multiline String automatically detects the common leading whitespace prefix (minimum indentation across all non-empty lines) and removes it from all lines. This makes it easy to indent your code visually without affecting the resulting string content.
@@ -4784,18 +2438,6 @@ fn = ->
4784 return str 2438 return str
4785``` 2439```
4786 2440
4787<YueDisplay>
4788
4789```yue
4790fn = ->
4791 str = |
4792 foo:
4793 bar: baz
4794 return str
4795```
4796
4797</YueDisplay>
4798
4799Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures. 2441Internal indentation is preserved relative to the removed common prefix, allowing clean nested structures.
4800 2442
4801All special characters like quotes (`"`) and backslashes (`\`) in the YAMLMultiline block are automatically escaped so that the generated Lua string is syntactically valid and behaves as expected. 2443All special characters like quotes (`"`) and backslashes (`\`) in the YAMLMultiline block are automatically escaped so that the generated Lua string is syntactically valid and behaves as expected.
@@ -4806,16 +2448,6 @@ str = |
4806 note: 'He said: "#{Hello}!"' 2448 note: 'He said: "#{Hello}!"'
4807``` 2449```
4808 2450
4809<YueDisplay>
4810
4811```yue
4812str = |
4813 path: "C:\Program Files\App"
4814 note: 'He said: "#{Hello}!"'
4815```
4816
4817</YueDisplay>
4818
4819# Module 2451# Module
4820 2452
4821## Import 2453## Import
@@ -4847,35 +2479,6 @@ do
4847 import "export" as {one, two, Something:{umm:{ch}}} 2479 import "export" as {one, two, Something:{umm:{ch}}}
4848``` 2480```
4849 2481
4850<YueDisplay>
4851
4852```yue
4853-- used as table destructuring
4854do
4855 import insert, concat from table
4856 -- report error when assigning to insert, concat
4857 import C, Ct, Cmt from require "lpeg"
4858 -- shortcut for implicit requiring
4859 import x, y, z from 'mymodule'
4860 -- import with Python style
4861 from 'module' import a, b, c
4862
4863-- shortcut for requring a module
4864do
4865 import 'module'
4866 import 'module_x'
4867 import "d-a-s-h-e-s"
4868 import "module.part"
4869
4870-- requring module with aliasing or table destructuring
4871do
4872 import "player" as PlayerModule
4873 import "lpeg" as :C, :Ct, :Cmt
4874 import "export" as {one, two, Something:{umm:{ch}}}
4875```
4876
4877</YueDisplay>
4878
4879## Import Global 2482## Import Global
4880 2483
4881You can import specific globals into local variables with `import`. When importing a chain of global variable accessings, the last field will be assigned to the local variable. 2484You can import specific globals into local variables with `import`. When importing a chain of global variable accessings, the last field will be assigned to the local variable.
@@ -4887,17 +2490,6 @@ do
4887 print concat ["a", tostring 1] 2490 print concat ["a", tostring 1]
4888``` 2491```
4889 2492
4890<YueDisplay>
4891
4892```yue
4893do
4894 import tostring
4895 import table.concat
4896 print concat ["a", tostring 1]
4897```
4898
4899</YueDisplay>
4900
4901### Automatic Global Variable Import 2493### Automatic Global Variable Import
4902 2494
4903You can place `import global` at the top of a block to automatically import all names that have not been explicitly declared or assigned in the current scope as globals. These implicit imports are treated as local consts that reference the corresponding globals at the position of the statement. 2495You can place `import global` at the top of a block to automatically import all names that have not been explicitly declared or assigned in the current scope as globals. These implicit imports are treated as local consts that reference the corresponding globals at the position of the statement.
@@ -4919,25 +2511,6 @@ do
4919 FLAG = 123 2511 FLAG = 123
4920``` 2512```
4921 2513
4922<YueDisplay>
4923
4924```yue
4925do
4926 import global
4927 print "hello"
4928 math.random 3
4929 -- print = nil -- error: imported globals are const
4930
4931do
4932 -- explicit global variable will not be imported
4933 import global
4934 global FLAG
4935 print FLAG
4936 FLAG = 123
4937```
4938
4939</YueDisplay>
4940
4941## Export 2514## Export
4942 2515
4943The export statement offers a concise way to define modules. 2516The export statement offers a concise way to define modules.
@@ -4962,26 +2535,6 @@ export class Something
4962 umm: "cool" 2535 umm: "cool"
4963``` 2536```
4964 2537
4965<YueDisplay>
4966
4967```yue
4968export a, b, c = 1, 2, 3
4969export cool = "cat"
4970
4971export What = if this
4972 "abc"
4973else
4974 "def"
4975
4976export y = ->
4977 hallo = 3434
4978
4979export class Something
4980 umm: "cool"
4981```
4982
4983</YueDisplay>
4984
4985Doing named export with destructuring. 2538Doing named export with destructuring.
4986 2539
4987```yuescript 2540```yuescript
@@ -4989,15 +2542,6 @@ export :loadstring, to_lua: tolua = yue
4989export {itemA: {:fieldA = 'default'}} = tb 2542export {itemA: {:fieldA = 'default'}} = tb
4990``` 2543```
4991 2544
4992<YueDisplay>
4993
4994```yue
4995export :loadstring, to_lua: tolua = yue
4996export {itemA: {:fieldA = 'default'}} = tb
4997```
4998
4999</YueDisplay>
5000
5001Export named items from module without creating local variables. 2545Export named items from module without creating local variables.
5002 2546
5003```yuescript 2547```yuescript
@@ -5006,16 +2550,6 @@ export.<index> = items
5006export["a-b-c"] = 123 2550export["a-b-c"] = 123
5007``` 2551```
5008 2552
5009<YueDisplay>
5010
5011```yue
5012export.itemA = tb
5013export.<index> = items
5014export["a-b-c"] = 123
5015```
5016
5017</YueDisplay>
5018
5019### Unnamed Export 2553### Unnamed Export
5020 2554
5021Unnamed export will add the target item into the array part of the exported table. 2555Unnamed export will add the target item into the array part of the exported table.
@@ -5033,23 +2567,6 @@ export with tmp
5033 j = 2000 2567 j = 2000
5034``` 2568```
5035 2569
5036<YueDisplay>
5037
5038```yue
5039d, e, f = 3, 2, 1
5040export d, e, f
5041
5042export if this
5043 123
5044else
5045 456
5046
5047export with tmp
5048 j = 2000
5049```
5050
5051</YueDisplay>
5052
5053### Default Export 2570### Default Export
5054 2571
5055Using the **default** keyword in export statement to replace the exported table with any thing. 2572Using the **default** keyword in export statement to replace the exported table with any thing.
@@ -5060,16 +2577,6 @@ export default ->
5060 123 2577 123
5061``` 2578```
5062 2579
5063<YueDisplay>
5064
5065```yue
5066export default ->
5067 print "hello"
5068 123
5069```
5070
5071</YueDisplay>
5072
5073# License: MIT 2580# License: MIT
5074 2581
5075Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\> 2582Copyright (c) 2017-2026 Li Jin \<dragon-fly@qq.com\>