Quick Master Lua 5.3--Debug Library (1)

Source: Internet
Author: User

Q: What is an activity function?

A: A function that has been called in the program but has not yet completed execution.

 function g()     --[[the function "G" is called but not done yet, is the active function.         So here is the information for the function "G". "Debug.getinfo (2)" Gets the information that is the function "F". ]]    Localx =Debug. GetInfo (1,"n") forKvinch Pairs(x) Do         Print(k, V)End End function f()     --The function "F" is called but not done yet, is the active function. So here is the information for the function "F".     Localx =Debug. GetInfo (1,"n") forKvinch Pairs(x) Do         Print(k, V)End     Print() g ()EndF ()--[[Result:namewhat Global name F namewhat global name G]]
Q: What is the call stack?

A:lua the stack used to store activity functions. Each thread has its own stand-alone call stack.

Q: What is the level of the call stack?

A: The stack level of the function that calls the Debug library function is 1, the stack level of the function that called the function is 2, and so on.

function foo()    -- 调用调试库的函数。    ...endfunction goo()    foo()endfunction hoo()    goo()end--[[ 被调用的调试库函数栈级别为0,"foo"的栈级别为1,"goo"的栈级别为2,"hoo"的栈级别为3。     如果还有别的函数调用"hoo()",则栈级别以此类推。]]hoo()    
Q: How can I view the call stack information?

A:

--[[debug.traceback ([Thread,] [message [, Level]])Print first"Message", and then from the first"Level"Stack level to start printing"Thread"The call stack information in the thread. If"Message"is not a string or"nil", the function does not do any processing to return directly"Message"。"Thread"The default is that the current thread,"Level"Default is1。 ]] function foo()Print (Debug.traceback ("This is traceback:") print () print (Debug.traceback ("Traceback from Stack_level 2:",2) print () print (Debug.traceback ({}))End function goo()Foo ()End function hoo()Goo ()EndHoo ()--[[Results:This is Traceback:stack traceback:e:\a. LUA:2:inch  function ' foo ' E:\a. LUA:8:inch  function ' goo ' E:\a. LUA: A:inch  function ' hoo ' E:\a. LUA: the:inchMain Chunk [C]:inch? Traceback fromStack_level2: Stack traceback:e:\a. LUA:8:inch  function ' goo ' E:\a. LUA: A:inch  function ' hoo ' E:\a. LUA: the:inchMain Chunk [C]:inch? Table00522F78]]
Q: How do I view function information?

A:

--[[debug.getinfo ([Thread,] f [, what])Returns a"Table", which contains threads"Thread"The functions in"F"By"What"Specifies the relevant information."Thread"The current thread is assumed by default."F"It can be either a function name or a numeric value, which represents the stack level of the function. If the function specified by the name does not exist, an error is given and if the function specified by the value does not exist, the return"nil"。 If"What"Not specified, all fields except the Legal line number table are returned by default: Source: Creates the function's"Chunk"'s name. If"Source"To' @ 'The function is defined in a file, and the' @ 'The next part is the file name. If"Source"To' = 'The next section is the user behavior to determine how to represent the source code. In other cases, this function is defined in a string, and"Source"That's the string. SHORT_SRC: A "printable version" of"Source", used for error messages.         Linedefined: The line number at the beginning of the function definition.         Lastlinedefined: The line number at the end of the function definition. What: If the function is a LUA function, it is a string"Lua"If it is a C function;"C"; if it is a"Chunk"Is the main part of the"Main"。 CurrentLine: The line in which the given function is executing. When the line number information is not available,"CurrentLine"is set to-1。               Name: A reasonable name for the given function. Because the functions in LUA are"First-class values", so they don't have a fixed name. Some functions may be the values of global composite variables, others may simply be saved in a"Table"In a domain.               Lua checks to see how a function is invoked to find a suitable name. If it cannot find a name, the field is set to"NULL"。 Namewhat: Used to explain"Name"Domain. The value can be"Global","Local","Method","Field","Upvalue"Or"", depending on how the function is called. (Lua uses empty strings to indicate that none of the other options are compliant) Istailcall: If the function is called as a tail call, this value is"true"。         In this case, the caller of the current stack level is not in the stack. Nups: Function's"Upvalue"Number. Nparams: Number of function fixed parameters (for C functions are always0)。 Isvararg: If the function is a variable-argument function"true"(for C functions are always"true")。         Func: the function itself.                      Activelines: Legal line Number table.                      The integer index in the table is used to describe which rows in the function are valid rows. A valid row is a line with actual code, that is, the line where you can place a breakpoint. Invalid rows include blank lines and only commented lines."What"You can specify the following parameters to specify the return value"Table"Contains the fields in all the above domains:' n ': Contains"Name"And"Namewhat"Domain' S ': Contains"Source","SHORT_SRC","linedefined","lastlinedefined"And"What"Domain' l ': Contains"CurrentLine"Domain' t ': Contains"Istailcall"Domain' u ': Contains"Nup","Nparams"And"Isvararg"Domain' F ': Contains"Func"Domain' L ': Contains"Activelines"field;]]--Simple Version "Debug.traceback ()".  function traceback()    LocalLevel =1     while true  Do        Localinfo = Debug.getinfo (level,"Sl")if  notInfo ThenBreakEnd        ifInfo.what = ="C"  Then     --is a C function?Print (Level,"C function")Else     --A Lua functionPrintstring.format("[%s]:%d], INFO.SHORT_SRC, Info.currentline))EndLevel = level +1    EndEnd
Q: How do I debug function local variable information?

A:

--[[debug.getlocal ([Thread,] f, local) returns the name and value of the local variable with the "local" index of the function at the stack level "F" in Thread "threads". "Thread" defaults to the current thread.     This function is used not only to access explicitly defined local variables, but also to include formal parameters, temporary variables, and so on.     The index of the first parameter in the function "F" or the first local variable defined is 1, followed by the increment of the sequential index value defined in the code, and only the active variable in the current scope of the function is evaluated. A negative index represents a mutable parameter. -1 refers to the first mutable parameter, and so on.     Returns "Nil" if there is no variable at the specified "local". If the specified "F" is out of bounds, an error is given.     (You can call "Debug.getinfo ()" To check if the stack level is legitimate) with ' (' variable names that start with a variable name that does not have a name (such as a control variable used for loop control, or a block of code that removes debugging information). "F" can also be a function. In this case, this function can only return the name of the "F" parameter. ]] function foo(A, b)     --1, 2    LocalX--3     Do Localc = A-BEnd    --"C" is scoped only between "do-end", so it is not counted in the function "foo".     LocalA =1    --4     while true  Do        LocalName, value =Debug. getlocal (1A--"a" here is "a" above "local A = 1".         if  notName Then  Break End        Print(name, value) A = a +1    --Index +1, next variable.     EndEndFooTen, -)--[[result:a B x nil a 4]]Print() fori =1,4  Do     Print(Debug. getlocal (foo, i))--Provide the function name, only the formal parameters can be printed. End--[[result:a b nil Nil]]--[[debug.setlocal ([Thread,] level, local, value) is relative to the function of "debug.getlocal ()" and assigns "value" to the "thread" thread at the stack level     The index of the function is a local variable of "local". "Thread" defaults to the current thread.     "Level" can only be specified as a stack and cannot be specified as a function name.     For index and exception return values, see the "debug.getlocal" function. If the execution succeeds, the function returns the name of the local variable. ]] function foo(A, b)     --1, 2    LocalX--3     Do Localc = A-BEnd    --"C" is scoped only between "do-end", so it is not counted in the function "foo".     LocalA =1    --4    Print(Debug. getlocal (1,1))--A ten    Debug. setlocal (1,1, -)Print(Debug. getlocal (1,1))--AEndFooTen, -)
Q: How to Debug "metatable" Information?

A:

--[[debug.getmetatable (value) returns "MetaTable" of "value" and returns "nil" if "value" does not have "metatable". Debug.setmetatable (value, table) sets "metatable" of "value" to "table" (which can be "nil"), and the function returns "value". ]]LocalT1 = {__index = function (table, key)         return "MetaTable 1"    End}LocalT2 = {__index = function (table, key)         return "MetaTable 2"    End}Localt = {}setmetatable(t, T1)Print(T1,Debug.getmetatable(t))- TABLE:00802C50 TABLE:00802C50Debug.setmetatable(T, T2)Print(T2,Debug.getmetatable(t))- table:00802d60 table:00802d60
Q: How to Debug "UserData" Information?

A:

--[[ debug.getuservalue(u)     返回关联在"u"上的Lua值。如果"u"不是"userdata",则返回"nil"。     debug.setuservalue(udata, value)     将"value"设置为"udata"的关联值。"udata"必须是一个"full userdata"。]]
Additional:

1. Use the functions in the debug library only as much as possible during the debugging process. First, the performance of some functions in the library is not excellent. Second, it breaks down some of the basic rules of the LUA language, such as that local variables defined in a function cannot be accessed externally. Finally, you don't want to see it in your final product, so you can use it debug = nil to eliminate the debug library while reducing the size of the final product.
2, debug.getinfo() for "Tail Calls", only the package function is counted into the stack level of the calculation, wrapping function does not count into,

function g()    localdebug.getinfo(1)    -- 这里获取的是函数"g"的信息。函数"f"不计入栈级别的计算。    forinpairsdo         print(k, v)    endendfunction f()    return g()endf()

So to see the package function information for "Tail Calls", please specify the function name directly.

Quick Master Lua 5.3--Debug Library (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.