Update lua-introduction.rst

gccjit-ravi534
Dibyendu Majumdar 7 years ago committed by GitHub
parent 8d75f9a922
commit c548cae775

@ -368,26 +368,28 @@ Here is how a protected call is done::
end
end
-- call foo() in protected mode
status,returnvalue = pcall(foo, 'hello') -- this is like calling foo('hello')
-- call foo('hello') in protected mode
status,returnvalue = pcall(foo, 'hello')
-- since this call should succeed, status will be true
-- returnvalue should contain 4.2
assert(returnvalue == 4.2)
-- call foo() again in protected mode
status, returnvalue = pcall(foo) -- call foo() without arguments
-- call foo() without arguments in protected mode
status, returnvalue = pcall(foo)
-- above will fail and status will be false
-- But returnvalue will now have the error message
assert(not status)
print(returnvalue)
-- above prints 'message expected'
The error handling mechanism works but has following issues:
The Lua error handling mechanism has following issues:
* The code that can raise errors must be a function as pcall() can only call functions
* The code that can raise errors must be encapsulated in a function as pcall() can only call functions
* The return values from pcall() depend upon whether the call terminated normally or due to an error - so caller needs to check the status of the call and only then proceed
* On raising an error the ``longjmp`` unwinds the stack - there is no mechanism for any intermediate objects to perform cleanup as is possible in C++ using destructors, or in Java, C++, Python using ``finally`` blocks, or as done by the ``defer`` statement in Go
* You can setup a finalizer on Lua user types that will eventually execute when the value is garbage collected - this is typically used to free up memory used by the value - but finalizers by their nature are not guaranteed to run in a deterministic manner
* You can setup a finalizer on Lua user types that will eventually execute when the value is garbage collected - this is typically used to free up memory used by the value - but you have no control over when the finalizer will run, hence relying upon finalizers for cleanup is problematic

Loading…
Cancel
Save