Type Checking और Conversion
type आपको बताता है कि एक value क्या है, और tonumber और tostring numbers और strings के बीच convert करते हैं।
In this page:
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
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!
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह उम्मीद करना कि type(nil) nil return करेगा न कि string "nil"
- यह भूल जाना कि tonumber bad input के लिए nil return करता है
- 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: