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

Type Checking और Conversion

type आपको बताता है कि एक value क्या है, और tonumber और tostring numbers और strings के बीच convert करते हैं।

Type Checking और Conversion

type function nil, boolean, number, string, table, function, thread, और userdata में से एक string की तरह return करता है। tonumber एक string को एक number में convert करता है, या जब यह नहीं कर सकता तो nil return करता है, और second argument की तरह एक base accept करता है। Lua automatically coerce भी करता है, इसलिए numeric strings पर arithmetic काम करता है और .. के साथ इस्तेमाल हुए numbers strings बन जाते हैं।

Note: arithmetic में इस्तेमाल करने से पहले tonumber के result में हमेशा nil check करें।

उदाहरण: Type checking and conversion

lua
print(type(print), type({}), type("x"), type(nil))
print(tonumber("42"), tonumber("3.5"), tonumber("abc"))
print(tonumber("ff", 16), tonumber("101", 2))
print("10" + 5, 10 .. 20)
print(tostring(true) .. "!")

-- Output:
-- function	table	string	nil
-- 42	3.5	nil
-- 255	5
-- 15.0	1020
-- true!
{# 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. यह उम्मीद करना कि type(nil) nil return करेगा न कि string "nil"
  2. यह भूल जाना कि tonumber bad input के लिए nil return करता है
  3. automatic coercion पर depend करना और surprises पाना
चैप्टर सारांश
  • type एक string name return करता है
  • tonumber failure पर nil return करता है
  • tostring किसी भी value को convert करता है
  • Strings और numbers arithmetic और .. में coerce होते हैं
🔒

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.