🐢

Introduction to Lua Programming Basics

Mar 28, 2025

Fundamentals of Programming with Lua

Getting Started with Lua

  • No prior coding experience needed.
  • Follow along in browser via lua.org.

Variables

  • Variable: A piece of stored data whose value can change.
  • Example: message = "Lua is awesome" print(message) -- Prints: Lua is awesome
  • Data Types:
    • String: Text data, e.g., "Lua is awesome".
    • Number: Numerical data, e.g., 5.
  • Variables can store various data types, and values can change.
  • Example of changing a variable: chicken = 10 result = chicken -- result is now 10 chicken = 25 -- Printing chicken will show 25, but result remains 10

Arithmetic with Variables

  • Perform arithmetic operations (addition, subtraction, multiplication, division) on numerical variables.
  • Example: result = chicken + 1 print(result) -- Outputs: 11
  • Errors occur if arithmetic is attempted on non-numeric types, e.g., strings.

Conditional Statements

  • If, Else If, Else Statements are used to run code based on conditions.
  • Example: if condition > 0 then message = 1 elseif condition < -10 then message = -1 else message = "no conditions met" end
  • Else If allows multiple conditional checks.

Loops

  • While Loop: Repeats a block of code while a condition is true. while message < 10 do message = message + 1 end
  • For Loop: Repeats a block a predetermined number of times. for i = 1, 3, 1 do pickle = pickle + 10 end
  • Iterators can be used within loops, e.g., i in a for loop.

Functions

  • Used to encapsulate code for reuse.
  • Defined using the function keyword.
  • Can accept parameters and return values. function increaseMessage(fu) return fu * 2 end local result = increaseMessage(5) -- result is 10

Comments

  • Single-line: Use --.
  • Multi-line: Use --[[ ]].
  • Used for explaining code or disabling code parts temporarily.

Variable Scope

  • Global Variables: Accessible anywhere in the program.
  • Local Variables: Restricted to where they are defined. local var = fu / 2

Tables

  • Unique Lua data structure to store sets of related data.
  • Example: testScores = {95, 87, 98} print(testScores[2]) -- Outputs: 87
  • Use table.insert() to add elements.
  • Tables can have properties attached. testScores.subject = "math"
  • Allows both integer and string indices.

Conclusion

  • Lua tables are versatile and useful for organizing data.
  • Encourage further exploration into Lua for game development or other applications.