← Back to Lua Course | Chapter 2: Variables & Types | Lesson 2 of 7

Local और Global Variables

Variables default से global होते हैं, इसलिए इन्हें अपने block के लिए private रखने के लिए local mark करें।

Local और Global Variables

local keyword के बिना assigned एक variable global है और table _G में रहता है। एक local variable सिर्फ उस block के अंदर visible है जहाँ यह declare हुआ, और access करने में faster है। एक ऐसे global को पढ़ना जो कभी assign नहीं हुआ error की बजाय nil देता है।

Note: लगभग हमेशा variables को local से declare करें, और globals को सिर्फ उन चीज़ों के लिए रखें जो आप truly share करते हैं।

उदाहरण: Local and global variables

lua
g = "global"
local l = "local"
print(_G.g, _G.l)

do
  local inner = "inside"
  print(inner)
end
print(inner)

local x = 1
do
  local x = 2
  print(x)
end
print(x)

-- Output:
-- global	nil
-- inside
-- nil
-- 2
-- 1
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. local भूल जाना और गलती से एक global बना देना
  2. यह उम्मीद करना कि एक local इसके block के खत्म होने के बाद भी visible रहेगा
  3. एक variable misspell करना और silently nil पढ़ना
चैप्टर सारांश
  • Undeclared assignment एक global बनाता है
  • local scope को block तक limit करता है
  • Globals _G में रहते हैं
  • Unknown globals nil हैं
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.