### Wire Basic Output Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/stringcall/builtins.txt Shows a simple example of printing multiple values to the console using the 'print' function in Wiremod Wire scripting. ```wire "print"(1, 2, "test") ``` -------------------------------- ### Wiremod Installation Guide Source: https://github.com/wiremod/wire/blob/master/README.md Provides instructions for installing Wiremod, the stable and canary versions, and related addons like AdvDupe2 and Wire Extras. Includes links to Steam Workshop and GitHub repositories, as well as Git commands for manual installation. ```Markdown # Wiremod [![License](https://img.shields.io/github/license/wiremod/wire?color=red)](LICENSE) [![Discord](https://img.shields.io/discord/231131817640460288?label=Discord&logo=discord&logoColor=ffffff&labelColor=7289DA&color=2c2f33)](https://discord.gg/H8UKY3Y) [![Workshop](https://img.shields.io/steam/subscriptions/160250458?logo=steam)](https://steamcommunity.com/sharedfiles/filedetails/?id=160250458) > An addon for [Garry's Mod](https://garrysmod.com) which adds entities that communicate via wires. It can be used to create robots, vehicles, computers and much more! ## ⬇️ Installation | Addon | Workshop | GitHub | | --- | --- | --- | |**Wiremod** (Stable) | [![Wiremod](https://img.shields.io/steam/subscriptions/160250458?logo=steam)](https://steamcommunity.com/sharedfiles/filedetails/?id=160250458) | https://github.com/wiremod/wire | |**Wiremod** (Canary) | [![Wiremod Canary](https://img.shields.io/steam/subscriptions/3066780663?logo=steam&color=orange)](https://steamcommunity.com/sharedfiles/filedetails/?id=3066780663) | https://github.com/wiremod/wire | |**AdvDupe2**| [![AdvDupe2](https://img.shields.io/steam/subscriptions/773402917?logo=steam)](https://steamcommunity.com/sharedfiles/filedetails/?id=773402917)| https://github.com/wiremod/advdupe2 | |**Wire Extras**| [None yet](https://github.com/wiremod/wire-extras/issues/113) | https://github.com/wiremod/wire-extras | For git, inside of `steamapps/common/Garrysmod/garrysmod/addons`, run ``git clone https://github.com/wiremod/wire``. ``` -------------------------------- ### Wiremod Wire Try-Catch Examples Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/try.txt Demonstrates basic try-catch blocks in Wiremod Wire scripting. Includes examples with empty catch blocks and catch blocks with typed string variables. ```Wiremod Wire try {} catch (E) {} try {} catch (Err:string) {} try {} catch (_) {} try {} catch (_:string) {} ``` -------------------------------- ### Full Example: File Write and Read Operations Source: https://github.com/wiremod/wire/wiki/E2-Guide:-File-Extension A complete example demonstrating writing to a file, triggering a load operation upon completion, and then printing the loaded file's content and the time elapsed. ```ruby @name File Write and Read @trigger none @strict fileWrite("test.txt", "Hello, World! " + curtime()) event fileWritten(Path:string, _:string) { fileLoad(Path) } event fileLoaded(Path:string, Data:string) { print(format("%s: %s \nTime: %f", Path, Data, curtime())) } ``` -------------------------------- ### Wiremod Lua: Loop and Control Flow Examples Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/loops/while.txt Demonstrates the usage of 'while' and 'do-while' loops, 'break' and 'continue' statements, and 'assert' for verifying conditions in Wiremod scripting. ```lua local Num = 0 while(Num < 1000) { Num++ if(Num == 500) { break } } assert(Num == 500) do { Num++ } while(Num < 1000) assert(Num == 1000) local Ran = 0 do { Ran = 1 } while (0) assert(Ran) ``` -------------------------------- ### Wire Select, Min, and Max Function Examples Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/stringcall/builtins.txt Demonstrates the usage of the 'select', 'min', and 'max' functions in Wiremod Wire scripting, showing how to select an element from a list and find the minimum or maximum of two numbers. ```wire assert( "select"(1, "test", "foo", "bar")[string] == "test" ) assert( "min"(1, 2)[number] == 1 ) assert( "max"(1, 2)[number] == 2 ) ``` -------------------------------- ### Full Wiremod File Queuing Example Source: https://github.com/wiremod/wire/wiki/E2-Guide:-File-Extension This is a comprehensive example combining file writing, listing, and loading operations using Wiremod's queuing system. It demonstrates the sequential execution of file operations and event handling for managing the process. ```ruby @name File Queues @trigger none @strict for(I = 1, 10) { if(fileCanWrite()) { fileWrite(format("manyfiles/%d.txt", I), format("This is file #%d!", I)) } else { break } } event fileWritten(_:string, _:string) { if(fileWriteQueued() == 0) { fileList("manyfiles/") } } event fileList(Path:string, Contents:array) { foreach(_:number, Name:string = Contents) { if(fileCanLoad()) { fileLoad(Path + Name) } else { break } } } event fileLoaded(Path:string, Data:string) { print(format("%s: %s", Path, Data)) } ``` -------------------------------- ### Wiremod Script Execution Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/regressions/2883.txt Demonstrates a simple Wiremod script that executes a loop, uses a switch statement, and asserts a condition. This example highlights basic scripting constructs within the Wiremod environment. ```wiremod ## SHOULD_PASS:EXECUTE Ran = 0 for(I = 1, 1) { switch (0xDEADBEEF) { default, break # Shouldn't break out of loop } Ran = 1 } assert(Ran) ``` -------------------------------- ### Wire Script: Nil Input Parameters and Undefined Methods Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/methods.txt Demonstrates handling of nil or default values for function parameters and how the scripting engine handles calls to undefined methods. It includes examples of using `noranger()` and catching runtime errors. ```wire function number number:nilInput(X, Y:ranger, Z:vector) { assert(Z == vec(1, 2, 3)) return 5 } assert( 1:nilInput(1, noranger(), vec(1, 2, 3)) == 5 ) if (0) { function number:undefined() {} } try { 1:undefined() error("unreachable") } catch(Err) { assert(Err == "No such method defined at runtime: undefined(n:)") } ``` -------------------------------- ### Wiremod Documentation and Contribution Guide Source: https://github.com/wiremod/wire/blob/master/README.md Guides users to the official Wiremod wiki for detailed documentation and outlines the process for contributing to the project, including submitting suggestions, bug reports, and pull requests with adherence to the developer style guide. ```Markdown ## 📖 Documentation You can find documentation [on our wiki](https://github.com/wiremod/wire/wiki) ## 🤝 Contributing > Before contributing to wiremod, take a look at the [code of conduct](https://github.com/wiremod/wire/blob/master/CODE_OF_CONDUCT.md). ### 💡 Suggestions To submit a suggestion, [use the discussions page](https://github.com/wiremod/wire/discussions/new?category=suggestions). ### 🐛 Bug Reports To submit a bug report, [make an issue](https://github.com/wiremod/wire/issues/new/choose). ### 🧑‍💻 Pull Requests Before making a PR, ensure your code follows the [developer style guide](https://github.com/wiremod/wire/wiki/Developer-Style-Guide). ``` -------------------------------- ### Wire String Formatting Examples Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/stringcall/builtins.txt Demonstrates the use of the 'format' function in Wiremod Wire scripting for various string formatting scenarios, including basic string insertion, quoted strings, and mixed data types. ```wire assert( "format"("%s", "test")[string] == "test" ) assert( "format"("%q", "test")[string] == "\"test\"" ) assert( "format"("%d %d %s", 52, 20, "test")[string] == "52 20 test" ) ``` -------------------------------- ### Wiremod E2 Switch Statement Example Source: https://github.com/wiremod/wire/wiki/E2:-Tips-and-Tricks Provides an example of using a 'switch' statement in Wiremod Expression 2 to handle multiple conditions based on a single variable. It demonstrates 'case' matching, 'break' statements, fallthrough behavior, and the 'default' case. ```golo switch(Command){ # The variable to check case "print", # do this when Command == "print" print("Hello") break # end of this block case "reset", # multiple cases are allowed case "restart", # do this when Command == "reset" or Command == "restart" reset() break case "save_and_exit", save_something() # notice the missing "break" here case "exit", # if there is no break, it continues on with the next block exit() # so exit() is ran in both cases, but save only in the top one break default, # ran when no case matches, this is optional error("command not found") } ``` -------------------------------- ### Wire Scripting: Variable Assignment and Assertions Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/types/number/delta.txt Demonstrates how to declare, assign, and assert values of variables in Wiremod's Wire scripting language. It includes examples of incrementing a variable and commenting out code. ```wire @persist X:number assert($X == 0) X = 5 assert($X == 5) # assert($X == 0) ( Unintentionally new behavior, :( X++ assert($X == 1) ``` -------------------------------- ### Wiremod Scripting: Void Return Functions Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/functions_const.txt Explains and demonstrates functions that do not explicitly return a value (void functions). Includes examples of functions with early returns and explicit void returns. ```lua function returnvoid() { if (1) { return } error("unreachable") } returnvoid() ``` ```lua function void returnvoid2() { return } returnvoid2() ``` ```lua function returnvoid3() { return void } returnvoid3() ``` -------------------------------- ### Wire Script: String Return Function Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/compiler/restrictions/fn_return_pass.txt Demonstrates a simple Wire script function that returns a string value. This is a basic example of function definition and return statements in Wiremod. ```wire function string nothing() { return "something" } ``` -------------------------------- ### Wiremod Switch Statement Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/regressions/2783.txt Demonstrates a switch statement with multiple cases, including returning values and triggering errors. It also includes assertions to verify the function's behavior. ```Wiremod function number test(N:number) { switch (N) { case 1, return 5 case 3, error("unreachable") case 2, return 2 case 5, error("unreachable") } return 1 } assert( test(1) == 5 ) assert( test(2) == 2 ) assert( test(4) == 1 ) ``` -------------------------------- ### Wire Script: Recursion and Sentinel Value Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/methods.txt Shows how to implement recursive functions in Wiremod Wire scripting. It includes a basic recursive function that counts down and a more complex example involving a global sentinel variable to track recursion depth. ```wire # Test recursion function number number:recurse(N:number) { if (N == 1) { return 5 } else { return This:recurse(N - 1) + 1 } } assert(1:recurse(10) == 14, 1:recurse(10):toString()) Sentinel = -1 function number:recursevoid() { Sentinel++ if (Sentinel == 0) { This:recursevoid() } } 1:recursevoid() assert(Sentinel == 1) ``` -------------------------------- ### Wiremod EGP Colored Text Example Source: https://github.com/wiremod/wire/wiki/E2:-EGP This example demonstrates how to use the Wiremod EGP system to draw a colored box and text on a screen. It covers clearing the screen, creating a box with a specific color, and adding text with custom font and color. ```golo @name Colored Text @inputs EGP:wirelink # wire this to the screen if(first() | ~EGP) { # E2 triggered by spawning the E2 or changing the EGP input if(->EGP) { # EGP is wired to something EGP:egpClear() # Clear screen contents EGP:egpBox(1, vec2(256, 256), vec2(200, 50)) # create a 200x50 box in the center of the screen, stored in slot 1 EGP:egpColor(1, vec(240, 60, 60)) # color the object in slot 1 (that box) red (decimal RGB values in a vector) EGP:egpText(2, "Hello World", vec2(256, 256)) # create a Hello World text object in the center of the screen, stored in slot 2 EGP:egpFont(2, "Roboto", 30) # Set font and font size for that text EGP:egpColor(2, vec(60, 240, 240)) # Color the text cyan } else { print("No EGP wired! Please wire the wirelink to a EGP screen") } } ``` -------------------------------- ### Wire Scripting: Error Handling and Assertions Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/regressions/3080.txt Demonstrates the use of try-catch blocks to handle errors and assert statements to verify expected outcomes in Wiremod scripting. Includes examples of catching errors thrown within conditional blocks and function calls. ```wire try { error("A") } catch(A:string) { assert(A == "A") } try { if(1) { error("B") } } catch(B:string) { assert(B == "B") } if(1) { try { error("C") } catch(C:string) { assert(C == "C") } try { if(1) { error("D") } } catch(D:string) { assert(D == "D") } let Fn = function() { error("F") } try { Fn() } catch(F:string) { assert(F == "F") } } ``` -------------------------------- ### Sample Code Snippets with Syntax Highlighting Source: https://github.com/wiremod/wire/wiki/Misc:-Wiki-Contribution-Guide Examples of sample code using recommended syntax highlighting languages: golo, ts, and ruby. These snippets demonstrate basic function definitions and printing output. ```golo function myFunction(MyVar:string) { print("Hello " + MyVar) } # prints 'Hello' followed by MyVar, golo ``` ```ts function myFunction(MyVar:string) { print("Hello " + MyVar) } # prints 'Hello' followed by MyVar, ts ``` ```ruby function myFunction(MyVar:string) { print("Hello " + MyVar) } # prints 'Hello' followed by MyVar, ruby ``` -------------------------------- ### Registering a Constant Source: https://github.com/wiremod/wire/wiki/Creating-an-E2-Core Registers a named constant value that can be accessed within Expression2. This example registers the mathematical constant Pi. ```lua E2Lib.registerConstant( "PIE", math.pi ) ``` -------------------------------- ### Wiremod Lookup Table Basics Source: https://github.com/wiremod/wire/wiki/E2:-Tips-and-Tricks Demonstrates the fundamental creation and usage of lookup tables in Wiremod. Shows how to initialize a table with key-value pairs, add new entries, check for existing entries, and retrieve values, including handling cases where an entry might not exist by providing a default value. ```golo # Create table once, using numbers as values Table = table("someKey" = 1, "someOtherKey" = 42, "STEAM_0:0:12345"=1) # Write to table Table[Key, number] = Value # Example usecases if(Table:exists(Key)){ ... # Check if entry exists } if(Table[Key, number]){ ... # Check if entry is !=0 (and exists) } Value = Table[Key, number] ?: 1337 # Read value from table or return a default value if entry doesn't exist ``` -------------------------------- ### Defining an E2 Operator Source: https://github.com/wiremod/wire/wiki/Creating-an-E2-Core Defines a custom operator for Expression2 using the preprocessor. This example demonstrates overloading the addition operator for a 'quaternion' type. ```lua e2function quaternion operator+(quaternion lhs, quaternion rhs) return { lhs[1] + rhs[1], lhs[2] + rhs[2], lhs[3] + rhs[3], lhs[4] + rhs[4] } end ``` -------------------------------- ### Array Count Operation in Wiremod Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/call.txt Shows how to get the number of elements in an array using the count() method. This is essential for iterating or processing array data. ```Wiremod array():count() ``` -------------------------------- ### Defining an E2 Function Source: https://github.com/wiremod/wire/wiki/Creating-an-E2-Core Defines a new function that can be called within Expression2 using the preprocessor syntax. This example shows a function that returns a random number. ```lua e2function number getANumber() return math.random() end ``` -------------------------------- ### Wiremod Script Execution and Type Assertion Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/types/number/index.txt Demonstrates executing a Wiremod script and asserting the type of a variable. It shows how to get a 'nowirelink' object and then use it to access a 'number' type associated with a string key. ```lua local X = nowirelink() assert(X:number("Foo") == X["Foo", number]) ``` -------------------------------- ### Wiremod Wire Project Configuration Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/_helloworld_.txt Shows the basic configuration for a Wiremod Wire project, including defining inputs, outputs, persistent variables, and triggers. ```Wirescript @name Hello World @inputs A B @outputs Add Sub Mul Div @outputs GreaterThan Highest Lowest @outputs Vector:vector @persist D @trigger all ``` -------------------------------- ### Calculate Launch Vector (Golo) Source: https://github.com/wiremod/wire/wiki/E2:-Physics Calculates the necessary acceleration vector to launch an object from a start point to a target point. It accounts for gravity and an optional additional height to arc the projectile. Drag is not simulated. ```golo function vector calcLaunchVector(Start:vector, Target:vector, AddHeight){ #[ Detailed version # Height difference, positive if target is higher than start local TargetHeight=Target:z()-Start:z() # Height at the maximum of the trajectory local PeakHeight=AddHeight+max(TargetHeight,0) # first assume we fire straight up, with start being at height 0 # Formula for peak height given upwards speed: `h_peak = v^2 / 2g` # Solving for v gives `v = sqrt(2g*h_peak)` local VerticalSpeed=sqrt(2*gravity()*PeakHeight) # This is the vertical speed we need to lauch at to reach the target peak height # Formula for distance fallen given starting velocity and elapsed time: `h = v*t - 1/2 * g*t^2` # Solving for t gives `t = (v+sqrt(v^2-2gh))/g` local Airtime = (VerticalSpeed+sqrt(VerticalSpeed^2-2*gravity()*TargetHeight))/gravity() # This is the time we spend from launching to reaching the *height* of the target, using our vertical launch speed # Note that how far we move horizontally during that time doesn't affect the result, so we can adjust horziontal speed indepentently # Now use the airtime to calculate the horizonal launch velocity local HorizontalDiff=vec2(Target-Start) # ignore z axis (height) local HorizontalVel=HorizontalDiff/Airtime # cover the whole horizontal distance during the flight time # This is adjusted to the projectile moves the exact horizontal difference to the target in the time it needs to reach the target height # So after the airtime, both height and horzontal position will be at the target, which means the projectile arrives perfectly # finally combine horizontal speed (2d vector), and vertical speed (1d "vector") into a 3d vector return vec(HorizontalVel, VerticalSpeed) ]# # Compact version local VerticalSpeed=sqrt(2*gravity()*AddHeight+max(Target:z()-Start:z(),0)) return vec(vec2(Target-Start)/(VerticalSpeed+sqrt(VerticalSpeed^2-2*gravity()*(Target:z()-Start:z()))/gravity()), VerticalSpeed) } ``` -------------------------------- ### EGP Touchscreen Example Source: https://github.com/wiremod/wire/wiki/E2-Guide:-EGP-Basics Demonstrates a simple touchscreen interface using an EGP screen. It clears the screen, draws a box with text, and detects user clicks within the box to change the text content. Requires wiring an EGP screen and a User entity. ```golo @name EGP Touchscreen @inputs EGP:wirelink User:entity # Wire both of these to the EGP screen @trigger none @strict function draw() { if(EGP) { # Same setup as above EGP:egpClear() EGPBox = EGP:egpBox(1, vec2(256, 256), vec2(200, 50)) # Note these are now globals EGPBox:setColor(vec(240, 60, 60)) EGPText = EGP:egpTextLayout(2, table( "text" = "Press here", "x" = 256, "y" = 256, "w" = 200, "h" = 50, "font" = "Roboto", "size" = 16, "r" = 60, "g" = 240, "b" = 240, "halign" = 1, "valign" = 1 )) } else { print("No EGP wired! Please wire the wirelink to a EGP screen") } } draw() event input(Input:string) { if(Input == "User") { # E2 triggered by User input changing if(User) { # if User is valid # To arrive here, the User input must have changed, and is currently a valid entity (so someone used the screen) let CursorPos = EGP:egpCursor(User) # get the exact coordinates the user is pointing at, as a 2d vector if(EGPBox:containsPoint(CursorPos)) { # if the cursor coordinates are between the top-left and bottom-right corners of the box in BOTH x and y, the user is pointing inside the box EGPText:setText(User:name() + " clicked inside the box!") # Change text of the text object } else { # not inside => outside EGPText["text"] = User:name() + " clicked outside the box!" # We can also use array indexing to change the text } } } else { draw() # Redraw if the screen changed } } ``` -------------------------------- ### Wiremod Array Initialization and Assignment Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/index.txt Demonstrates how to initialize an array and assign a value to a specific index in Wiremod Wire scripting. It shows the basic syntax for creating an array and setting its elements. ```Wiremod A = array() A[1, number] = 5 ``` -------------------------------- ### Wiremod Scripting: Table Creation with String Key Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/table.txt Illustrates creating a table in Wiremod scripting with a string key and a variable assignment. ```lua K = "" table(K = 5, "" = 5) ``` -------------------------------- ### Wiremod Holo Creation and Control Source: https://github.com/wiremod/wire/wiki/E2:-Tips-and-Tricks Demonstrates creating a holo entity, setting its properties (alpha, material), and controlling its movement over time using timers and persisted table values. ```golo @name HoloBubble @inputs Spawn @persist P:table if(first()){ # default settings P=table( "speed"=2, "scale"=1, "alpha"=127, "material"="models/debug/debugwhite", "lifetime"=50 ) runOnChat(1) # We'll need this later } elseif(~Spawn & Spawn){ # Button pressed holoCreate(1, entity():pos(), vec(P["scale",number]), ang()) holoAlpha(1, P["alpha",number]) holoMaterial(1, P["material",string]) P["holo age",number]=0 # Just create new entries on the fly stoptimer("move") # stop any old timers timer("move", 100) } elseif(clk("move")){ if(P["holo age",number] 0.125 x 7 # soundDuration 5000 ":upper()" max(1, 2) assert( opcounter() == 5021 ) function number:usermethod() {} 1:usermethod() # + 5 assert( opcounter() == 5021 ) function userfunction() {} userfunction() # + 5 soundDuration("") ``` -------------------------------- ### Wiremod Array Concat Source: https://github.com/wiremod/wire/wiki/e2-docs-array Concatenates elements of an array. Supports specifying a start index or a range (start and end index) for concatenation. ```APIDOC Array:concat(Number Startindex) Concatenates all values in the array, starting at the specified index. Array:concat(Number Startindex, Number Endindex) Concatenates all values in the array, starting at Startindex and ending at Endindex. ``` -------------------------------- ### Wiremod Chat Event Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/events.txt Shows how to handle chat events in Wiremod scripting. This event is triggered when a player sends a chat message. ```lua event chat(_:entity, _:string, _) { } ``` -------------------------------- ### Interactive Selection Menu Source: https://github.com/wiremod/wire/wiki/E2-Guide:-EGP-Basics This example builds upon the list concept to create an interactive menu. It displays a list of E2 types and allows the user to select an item. The implementation uses a bounding volume hierarchy approach to efficiently check for user interaction with the list items. ```golo @name Interactive Typelist @inputs EGP:wirelink User:entity @persist List:table ListStart:vector2 ListEnd:vector2 ListSpacing CurrentlySelected:egpobject @persist ContentText:egpobject @trigger none @strict ``` -------------------------------- ### WireScript Compilation Failure Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/compiler/restrictions/fn_void_param.txt Illustrates a scenario marked for compilation failure in Wiremod Wire scripting, indicated by the 'SHOULD_FAIL:COMPILE' directive. ```WireScript ## SHOULD_FAIL:COMPILE function test(X:void) {} ``` -------------------------------- ### Wiremod Scripting: Nil Input and Undefined Functions Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/functions.txt Shows how to handle nil inputs for function parameters and demonstrates error handling for calling undefined functions using a try-catch block. ```lua function number nilInput(X, Y:ranger, Z:vector) { assert(Z == vec(1, 2, 3)) return 5 } assert( nilInput(1, noranger(), vec(1, 2, 3)) == 5 ) if (0) { function undefined() {} } try { undefined() error("unreachable") } catch(Err) { assert(Err == "No such function defined at runtime: undefined()") } ``` -------------------------------- ### Wiremod Tick Event Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/events.txt Demonstrates the basic structure of a tick event handler in Wiremod scripting. The tick event is called every frame. ```lua event tick() { } ``` -------------------------------- ### Wiremod Player Use Example Source: https://github.com/wiremod/wire/wiki/Expression-2-Events This example demonstrates how to use the `playerUse` event in Wiremod. It triggers when a player uses a prop and logs the player and the entity they used. ```golo event playerUse(Player:entity, Entity:entity) { print(Player, "just used the prop", Entity) } ``` -------------------------------- ### Wiremod Shortcuts with Lookup Table Source: https://github.com/wiremod/wire/wiki/E2:-Tips-and-Tricks Demonstrates using lookup tables to create shortcuts or aliases for string values, such as model names in Wiremod. This example shows how to map short names to full model paths and retrieve them efficiently, comparing this method to traditional if-else statements. ```golo @persist Models:table if(first()){ Models = table( "short_straight" = "models/sprops/trans/train/track_s01.mdl", "straight" = "models/sprops/trans/train/track_s03.mdl", "long_straight" = "models/sprops/trans/train/track_s06.mdl", "tight_turn" = "models/sprops/trans/train/track_t90_01.mdl", "wide_turn" = "models/sprops/trans/train/track_t90_01.mdl" ) ... } ... local Input = ... # Get input, maybe from chat command # Check lookup table if there is a entry for the input. If the result is empty (no entry), just use the input directly local FinalModel = Models[Input, string] ?: Input propSpawn(FinalModel, ... , 1) ``` ```golo local FinalModel = "" if( Input == "short_straight" ){ FinalModel = "models/sprops/trans/train/track_s01.mdl" } elseif( Input == "straight" ){ FinalModel = "models/sprops/trans/train/track_s03.mdl" } ... elseif( Input == "wide_turn" ){ FinalModel = "models/sprops/trans/train/track_t90_01.mdl" } else{ FinalModel = Input } ``` -------------------------------- ### WireScript Null-Coalescing Operator Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/ternary.txt Shows the null-coalescing operator (?:) in WireScript, which provides a default value if the left-hand operand is null or undefined. Examples are provided for numeric and string types. ```WireScript 5 ?: "a" ?: ``` -------------------------------- ### Draw Colored Text and Box on EGP Source: https://github.com/wiremod/wire/wiki/E2-Guide:-EGP-Basics This example demonstrates how to clear an EGP screen, draw a colored box, and display formatted text using the EGP system. It includes error handling for missing EGP connections and redraws the content on input changes. ```golo @name Colored Text @inputs EGP:wirelink # wire this to the screen @trigger none @strict function draw() { if(EGP) { # if EGP is valid EGP:egpClear() # Clear screen contents let Box = EGP:egpBox(1, vec2(256, 256), vec2(200, 50)) # Create a 200x50 box in the center of the screen, at index 1 Box:setColor(vec(240, 60, 60)) # Color the object red using RGB values in a vector EGP:egpTextLayout(2, table( # Create a TextLayout object in the center of the screen, at index 2 "text" = "Hello, World!", "x" = 256 - 100, "y" = 256 - 25, "w" = 200, "h" = 50, "font" = "Roboto", "size" = 30, "r" = 60, "g" = 240, "b" = 240, # Colors the text cyan "halign" = 1, "valign" = 1 # Centers the text in the TextLayout )) } else { print("No EGP wired! Please wire the wirelink to a EGP screen") } } draw() # Draw when E2 is spawned event input(_:string) { draw() # Draw when input changes } ``` -------------------------------- ### Wiremod Wire: Basic Function Definitions and Calls Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/functions.txt Demonstrates the definition of a basic function that does nothing and how it's called. Also shows a function with an incomplete return statement. ```WireScript function unimplemented(_) {} unimplemented(5) ``` ```WireScript function f() {} function r() { return } ``` -------------------------------- ### Example: Rotating a Vector 90 Degrees About X-Axis Source: https://github.com/wiremod/wire/wiki/Quaternions-Guide-by-Fizyk Provides a step-by-step example of rotating the vector [3,5,-2] by 90 degrees about the X-axis using quaternions. ```Mathematics x = 90 degrees, v = [1,0,0] q = cos(45) + [1,0,0]*sin(45) = 0.707 + 0.707*i 1/q = 0.707 - 0.707*i w = 3i + 5j - 2k Rotated_w = (0.707+0.707*i)(3i+5j-2k)(0.707-0.707*i) = 3i + 2j + 5k Rotated vector: [3,2,5] ``` -------------------------------- ### Wiremod Scripting: Recursion Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/functions.txt Demonstrates recursive function calls, both with a numeric return value and a void return type. Includes an example of a recursive function that modifies a global variable. ```lua # Test recursion function number recurse(N:number) { if (N == 1) { return 5 } else { return recurse(N - 1) + 1 } } assert(recurse(10) == 14, recurse(10):toString()) Sentinel = -1 function recursevoid() { Sentinel++ if (Sentinel == 0) { recursevoid() } } recursevoid() assert(Sentinel == 1) ``` -------------------------------- ### Wiremod Scripting: Basic Table Creation Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/table.txt Demonstrates the basic usage of the 'table' function in Wiremod scripting to create a table with integer values. ```lua table(1, 2, 3) ``` -------------------------------- ### Basic Arithmetic and Printing in Wiremod Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/call.txt Demonstrates fundamental operations like finding the minimum of two numbers and printing output to the console. These are common building blocks for scripting. ```Wiremod min(1, 2) print("foo", 2) ``` -------------------------------- ### Wiremod Scripting: Basic Function Execution and Assertions Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/functions_const.txt Demonstrates the basic execution of a function and verifies its side effects using assertions. It also shows how function calls are processed in sequence. ```lua @strict # Ensure functions get called in the first place Called = 0 function myfunction() { Called = 1 } myfunction() assert(Called) ``` -------------------------------- ### Wiremod Lua Compile Failure Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/compiler/restrictions/fn_return_switch.txt Demonstrates a function in Wiremod Wire scripting that is designed to fail compilation. It includes a switch statement with invalid break placements and default cases. ```lua function string failure() { sswitch (5) { case 2, break default, break # 'break' does not return a value or cause a runtime error, just early returns switch. } } ``` -------------------------------- ### Wire Scripting: Function Definitions Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/compiler/restrictions/lambda/variadic_param.txt Demonstrates defining functions in Wire scripting. The first function accepts an array of arguments, while the second accepts a table of arguments. ```lua const X = function(...A:array) {} const Y = function(...A:table) {} ``` -------------------------------- ### Wiremod E2 Find Filters - Examples Source: https://github.com/wiremod/wire/wiki/E2:-Find-Functions Provides examples of using Wiremod's E2 find filter functions with Lua patterns for class and entity matching. ```lua findIncludeClass("prop") # All entites whose class contains "prop", ie "prop_physics" or "prop_vehicle" findIncludeClass("^prop_physics$") # Matching exactly "prop_physics", ie not "prop_physics_entity" findIncludeClass("^gmod_wire_[eh]") # Class begins with "gmod_wire_e" or "gmod_wire_h" (Using lua patterns) findIncludeEntity(entity():isWeldedTo()) # Entity the E2 is placed on findIncludePlayerProps(owner()) # All props owned by E2 owner ``` -------------------------------- ### Wiremod Table Initialization and Iteration Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/regressions/3325.txt Demonstrates initializing tables with sequential and key-value pairs, and iterating through them using foreach loops. Includes type-safe access and assertions for data validation. ```wire let A = table(1, 2, 3, "four", vec(5)) let B = table(1 = 1, 2 = 2, 3 = 3, 4 = "four", 5 = vec(5)) let Count = 0 function err(K:number, X:string, V:string) { return format("Failed at key %d with values [%s, %s]", K, X, V) } foreach(K:number, V:number = B) { Count += K let X = A[K, number] assert(X == V, err(K, toString(X), toString(V))) } assert(Count == 6) foreach(K:number, V:string = B) { Count += K let X = A[K, string] assert(X == V, err(K, X, V)) } assert(Count == 10) foreach(K:number, V:vector = B) { Count += K let X = A[K, vector] assert(X == V, err(K, toString(X), toString(V))) } assert(Count == 15) ``` -------------------------------- ### Wiremod Scripting: Table Creation with Variable Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/parser/table.txt Shows how to create a table in Wiremod scripting using a variable for one of the arguments. ```lua N = 5 table(N = 1, 2 = 2) ``` -------------------------------- ### Wire Scripting: Foreach Loop with Break Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/loops/foreach.txt This example illustrates how the 'break' statement can be used within a 'foreach' loop to exit the loop prematurely. It includes assertions to ensure the loop terminates as expected. ```wire # Ensure break works foreach(K: number, V:number = array(1, 2, 3, 4)) { assert(K == 1, "Should never iterate past break") if (1) { break } error("unreachable") } ``` -------------------------------- ### Wiremod Scripting: Recursive Function Calls Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/functions_const.txt Provides examples of recursive functions, including a function that returns a number and a function that modifies a global variable through recursion. It tests the base case and recursive step. ```lua # Test recursion function number recurse(N:number) { if (N == 1) { return 5 } else { return recurse(N - 1) + 1 } } assert(recurse(10) == 14, recurse(10):toString()) ``` ```lua Sentinel = -1 function recursevoid() { Sentinel++ if (Sentinel == 0) { recursevoid() } } recursevoid() assert(Sentinel == 1) ``` -------------------------------- ### Nil Input Parameters and Conditional Logic Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/methods_const.txt Shows how to handle nil or default values for function parameters and demonstrates conditional execution of code blocks. ```wire function number number:nilInput(X, Y:ranger, Z:vector) { assert(Z == vec(1, 2, 3)) return 5 } assert( 1:nilInput(1, noranger(), vec(1, 2, 3)) == 5 ) Ran = 0 if (0) { function number:constant() { Ran = 1 } } 1:constant() assert(Ran) ``` -------------------------------- ### Lua Function Compilation Failure Example Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/compiler/restrictions/fn_return.txt Demonstrates a basic Lua function in Wiremod that is intended to fail compilation. This serves as an example for understanding compilation errors within the Wiremod scripting environment. ```lua function string nothing() {} ``` -------------------------------- ### Wire Script: Return Values and Array Handling Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/userfunctions/methods.txt Illustrates different ways functions can return values, including simple numbers and array manipulations. It tests returning static values, values derived from array elements, and returning references to arrays. ```wire # Ensure functions return properly function number number:returning() { return 5 } assert(1:returning() == 5) function number number:returning2(X:array) { return X[1, number] + 5 } assert(1:returning2(array(5)) == 10) assert(1:returning2(array()) == 5) function array number:returningref(X:array) { return X } local A = array() assert(1:returningref(A):id() == A:id()) ``` -------------------------------- ### Wire Script: Number Return Function with If-Else Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/compiler/compiler/restrictions/fn_return_pass.txt Illustrates a Wire script function that returns a number, incorporating an if-else conditional statement. This example shows how to implement basic decision-making within scripts. ```wire function number deadcase() { if (1) { return 2158129 } else { return 2321515 } } ``` -------------------------------- ### Wire Scripting: Continue Preventing Iteration Bleed Source: https://github.com/wiremod/wire/blob/master/data_static/expression2/tests/runtime/base/loops/foreach.txt This example shows how 'continue' correctly prevents code from executing in the same iteration, ensuring that loop variables are updated only in subsequent iterations. It uses assertions to confirm this behavior. ```wire # Ensure continue does not bleed into next iteration local Inc = 1 foreach (K:number, V:number = array(1, 2, 3, 4)) { assert(K == Inc, "Continue bled into another iteration") Inc++ if (1) { continue } error("unreachable") } ```