Menu
CoddyTech

Names and Local Scope

Lesson 3 of 48 in Coddy's Lua for GDScript Developers course.

GDScript requires a variable declaration such as var amount = 6; its indentation defines the block containing that local. Lua uses local amount = 6 and explicit block endings. A standalone do ... end can give temporary values a smaller scope without introducing a condition. A new local with the same name shadows an outer local until the block ends. Assignment without local instead updates an existing visible variable, or a global when no local binding exists. This differs from a GDScript member declaration: a Lua top-level assignment does not create a field on an implicit script instance. Declare temporary arithmetic results locally.

GDScript 4

extends SceneTree

func _init():
	var amount = 6
	if true:
		var doubled = amount * 2
		print(doubled)
	print(amount)
	quit()

Lua 5.1

local amount = 6
do
  local amount = amount * 2
  print(amount)
end
print(amount)

Porting trap

In Lua, amount = amount * 2 updates the visible variable. Add local when the inner calculation should leave the outer value intact.

challenge icon

Challenge

Easy

Input is one integer n. Create a local doubled value inside a block. Return the original n and doubled value as n:doubled.

Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Try it yourself

local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for GDScript Developers

Practice on your own: Online Lua compiler