S&box Wiki

Revision Difference

From_Lua_to_CSharp#528934

<cat>Dev.Intro</cat> <title>From Lua to C#</title> # What is this guide This is meant to give an idea of the major differences between Lua and C#. # Comments ```lua -- Lua comments start with two minus signs --[[ Lua multiline comment example --]] ``` ```csharp // csharp comments start with two slashes, like most other languages /* csharp multiline comment example */ ``` # Global Variables ```lua -- you can define globals anywhere globalVar = 100 ``` ```csharp public class MyClass { // globals need to be in a class public static int GlobalVar = 100; } ``` # Variable Types ```lua -- Variables in Lua don't have a static type and can store any data local a = 100 a = "Hello" a = function() print( "Hi" ) end ``` ```csharp var a = 100; // Translated as "int a = 100;" because 100 is an int a = "Hello"; // Error: can't assign a string to an int ``` # Numbers ```lua local a = 100 a = 5.5 a = -300.1 ``` ```csharp int a = -300; uint b = 333333; //unsigned integer⤶ float c = 3.1111; // 6-9 digit after point precision⤶ double d = -500.888; // 15-17 digit after point precision⤶ decimal e = 131245.134325 // digit after point precision⤶ ```⤶ ⤶ # Strings⤶ ⤶ ```csharp⤶ String a = "hello world";⤶ ⤶ Console.WriteLine(a); // Console output: "hello world"⤶ ```⤶ ⤶ # Special types⤶ ⤶ ```csharp⤶ bool a = true; // or false. Commonly used in branching statements and conditional loops⤶ // The null keyword is a literal that represents a null reference, one that does not refer to any object⤶ object b; // Base type of all other types ⤶ uint b = 333333;⤶ double d = -500.888;⤶ ``` # Collections ```lua local stuff = { 1, 2, 3, "Oh", "Hi", "Mark", { myFunc = function() end } } ``` ```csharp var numbers = new int[3] { 1, 2, 3 }; var strings = new List<string> { "Oh", "Hi", "Mark" }; var functions = new Dictionary<string, Action> { ["myFunc"] = () => { } }; ``` # Member Access In Lua anything is accessible from anywhere as long as you have a reference. ```lua -- myFile.lua myTable = { field = 100 } ``` ```lua -- otherFile.lua print( myTable.field ) -- 100 ``` In C# things can be **public**, **private**, **protected** and **internal**. ```csharp // MyClass.cs public class MyClass { public static void PublicMethod() { ... } protected static void ProtectedMethod() { ... } private static void PrivateMethod() { ... } } ``` ```csharp // OtherClass.cs public class OtherClass : MyClass { public static void Test() { MyClass.PublicMethod(); // OK MyClass.ProtectedMethod(); // We inherit from MyClass so OK MyClass.PrivateMethod(); // Error: PrivateMethod is private } } ```⤶ ⤶ ⤶ # Type converation⤶ ⤶ In C# values can be converted to another type⤶ ⤶ ```csharp⤶ int a = 5;⤶ ⤶ String b;⤶ double c;⤶ int d;⤶ ⤶ b = a.toString(); // 5 -> "5"⤶ c = a.toDouble(); // 5 -> 5.0⤶ d = Int32.Parse(b) // "5" -> 5⤶ //etc...⤶ ```