A story triggered by global variables!

A story triggered by global variables!


Kobe asked: "Do you know what Los Angeles is like at four o'clock every morning ?" I haven't seen it, but I often see it at four o'clock in the Baiyun District of Guangzhou .

Did you look at the figure following yourself in the morning sun and said: "I get up earlier than a chicken and sleep later than a dog. Maybe this is my last struggle."

Wake up from sleep

I have a habit of freeing up half an hour to read at noon. When I saw 1 o'clock at noon that day, I was really a little sleepy, so I hurriedly closed the book and slept in a chair, dreaming! Suddenly I was pushed to wake up by my colleague (girl): "Hurry up, get up and help me see, something is wrong!"

I opened my eyes and saw my colleague already sweating profusely, looking at me nervously, as if holding a life-saving straw; a little bit of tears.

"It's raging, what's the matter? Is there an earthquake?"

"Wocao (it's probably in a hurry), no, no, there is a problem with the online activity, please help me see it, I have read it several times, and I can't find the problem."

"What activity, why don't I know?"

"It's a 520 Valentine's Day event operated two days ago ."

"Oh, what's the specific problem online now?"

"Online users send props and gifts on the leaderboard every day, and the rankings of some people will be distributed according to the rewards for the first place."

"Isn't it? How many users have been affected?"


Users now. "

Look dumbfounded . At that time, my heart was a little broken. This affected the number of people and the props are valuable (rmb). Wouldn't it be reported and deducted points? Suddenly I remembered that I had just stepped into the programmer industry many years ago because I was doing activities

code review
The code did not see the problem, resulting in loss
And customer complaints, it was the boss, operations manager, test manager of various DISS ( overview of the Company ); night a man standing in a corner of the Bund: secretly weeping , others also photographed. The cold wind on the Bund also pierced my heart.

"Which branch is the code in, send me the code and let me see it? Didn't you give me a review of the code?"


, It is this branch, and the enterprise WeChat sent it to me soon. "

I looked at her helpless eyes, now I have become dependent.

"Don't worry, I'll look at the code first!"

I looked at it for a few minutes (more than 1,000 lines of code), and basically the problem has been determined. It is estimated that she saw me stop tumbling the code, and the atmosphere has eased a lot.

"Did you not see

lua specification
wiki documentation? Don't know the prohibition
Global variable
Well? "

"What? Did I use global variables? I don't know, I'm useless, isn't it the same?"

Looking at the flustered explanation, I stopped talking . How should I calmly talk to her about my details and deal with the problem? I made a very low-level problem that could have been avoided but made a mistake.

"Put your head over and see here, here and here, is it right? You set the global variable of the props globally, but the value of the variable was changed during the query below, resulting in users other than the first one getting the first place Rewards; global data is



lua language
Have you ever understood the global variables and local variables in the specific?
Global variable
: As the name implies, the life cycle is global, the entire lua file can be accessed and used, and you can set the complete local variable in
_G table
Visit; exist
Contaminated documents
The variables are troublesome to maintain.
Local variable
: Only in certain specific
Within range
Valid variables, called local variables, are modified with local; therefore, local variables are usually used as much as possible for the convenience of maintenance.

"Oh, that's the case. I read other people's code and write it like this, so I copied it. Who knows that this kind of thing happens."

As a two-year back-end development, you can t just

, To be clear why others write this way? The document also needs to be read, I am like a big brother educating a little sister (

"I don't want to, isn't this just switching from java language to lua language? Where do you know so much?"

I'm mad , isn't this mad at me! The document is given to you, and the precautions are also written, and it is also marked in red: "

Tell the important thing three times

"Modify these places, submit the test environment , find the test again, this kind of inevitable problem, did not test it out! Needed later

This time the problem"


Again look ignorant force : before and after the change in attitude which is too big, and now the little girl are so Haoheng Well? Taking my new colleague is really exhausting me. Fortunately, it's a pretty girl, otherwise I will be angry to teach, it is really rare in our line of beautiful back-end girl paper. The whole group is just these few sister papers, she is the most

,Definitely is
Panda level
Of protection.

"What's up, what's up, you can't ask if you don't understand, who told me to be such a dish? Please have afternoon tea in the afternoon."

It's so arrogant , I can't bear it! But I heard there was afternoon tea: "It's okay, it's okay, when the change is finished and it is online, I will tell you in detail about the use of global variables and local variables"!

Evening dusk

It s getting off work, and I m concentrating on thinking about problems, looking back at what I did today and what I haven t done yet, and arrange my work for tomorrow! Suddenly appeared in the ear:

"Are you finished? I want to ask you about the bug at noon next time?"

"Don't show up suddenly, it scares me so much, are you thinking about something?"

Most programmers are very confident or even arrogant about the code they write. You can often hear in their ears: " Fuck, it's impossible. I have tested it clearly and it will not go wrong. You restart or you Give it a try? " Actually, I have secretly ran into the test environment to see it by myself, and quickly repaired it. Then tell the test: " I am indeed okay, you can look at it again !". Take a look at the test: "Did I get it wrong. I replied that it s okay."

"I usually tell you more

wiki documentation
, The organizational chart above,
redis cluster
mysql machine
Live more in different places
Wait, there are even pits you usually encounter, you have to take the initiative to see and learn! "

"Walk around, let's take the computer to a small meeting room for a chat!"

Nervous : Do you have to do that? Just find a chair to sit next to and chat, what should I do if others see it? Will it be misunderstood,

I have thoughts about her
? In this big group who looked at her, how many pairs of eyes were staring at her, and her back trembled.

"Don't make the atmosphere so tense, it makes me very uncomfortable!"

"Simply chat, find a place where there are few people to ask questions, don't wait for everyone to hear it, and say that I'm stubborn!"

" Then you now know that Lua is basically not recommended to use

Global variable
, And let use
Local variable

"I don't know, tell me something!"

## Then you have to remember, I will tell you again carefully, next time you can't make such a low-level mistake ## There are two main reasons why global variables are not recommended: In order to avoid naming conflicts caused by setting global variables, which will pollute the entire project, so try to use local variables Access to local variables is faster than global variables Copy code

"Then you tell me why it will affect other files?"

print ( "*********************I am a global variable********************** ****" ) global_variable = function (...) name = "I am A Mu" end global_variable() - call the function print (name) print ( "*********************I am a local variable ********************* ****" ) local_variable = function (...) local age = 26 end local_variable() - call the function print (age) print ( "*********************Clear global variable value ************************ **** " ) _G .name = nil Print (name) copying the code

"Look at the above, will the result be a magic horse?"

"I must be A Mu, 26, I am A Mu!"

I was almost out of a heart attack by you. Take a look at the result set below.

*********************I am a global variable *************************** * I am Amu *********************I am a local variable *************************** * nil nilcopy the code

"Is it so amazing? How come in the end

Global variable
Why is it worthless?"

"Do you want to know the reason?"

"Think about it, tell me quickly, it's kind of interesting"

Actually what we declared

Global variable
Will be stored in
Big G table
, _G is a table that saves all the lua used
Global function
Global variable
, We can visit like
Same visit
Value in

print ( "*********************_G table************************ **" ) - First set a local variable in order to verify that _G only stores global variables and global functions local sex = 1 - Big G table is a table and is a key-value pair, so use pairs for i,v in pairs ( _G ) do Print (I, V) End duplicated code

Look at the execution results :

********************* _G table************************** name I am A Mu - this is the global variable we just set table table : 0x7faba8c036b0 dofile function : 0 x1007b697d assert function : 0 x1007b684e _G table : 0 x7faba8c02770 string table : 0 x7faba8c04fc0 io table : 0 x7faba8c04260 ipairs function : 0 x1007b6aa8 toString function : 0 x1007b72a8 ........ ..................... debug table : 0 x7faba8c04b80 require function : 0 x7faba8c03d30 copy the code

"Oh, that's it, I know why this problem occurred in my morning activity, because I declared a global variable in the header of the file and modified it in other methods, which caused the value I got to change again. !"

"You are really smart,

'One click to break'
, me, me, me, it's really hard. "

"Why, you can't teach me as a Lua language Xiaobai? What's more, I'm still a sister paper, don't you have a bit of pity and cherishment ? Humph~~~"

"Fine, I can teach you! Now that I understand, I can go back from get off work, right?"

"Wait, I have another question, don't you say that accessing local variables is faster than global variables? How do you understand this? "

"You don't want me to get off work, I still want to go back and be a bloody meal! You have to have it, let me tell you, who called you the most beautiful boy in the whole group"

"I am the most beautiful girl in the group, not a boy!"

After Lua version 5.0, it uses a similar

Virtual mode of register
Lua use
To store its registers. Each function lua will
Allocate a stack
, Store the activity data in the function; Lua's compiler stores the local variable to the register, and the operation of the local variable is equivalent to the direct operation of the register of the global variable must first obtain the variable, and then it can be further operated , Naturally local variables are faster than global variables. To know
Memory access speed is not as fast as registers
Yes, and Lua's global variables are accessed through the table, which is equivalent to one more layer in the middle
Indirect access
, It must be much slower than local variables

"I'm already a little dizzy, can you give me an example to prove that a bunch of concepts are not as good as a case, hee hee ."

print ( "*********************Global variable and local variable access speed******************* *******" ) ### Global Variables sum = 0 - declare a global variable value for i = 1 , 100000 do sum = sum + i end print (sum) print ( os . clock ()) - returns an approximate value of the CPU time used by a program ### Local variables local sum = 0 - declare a local variable value for i = 1 , 100000 do sum = sum + i end print (sum) print ( os . clock ()) ### Execution result set ~ lua hello.lua *********************Access speed of global variables and local variables ************************ **** 5000050000 0.006693 5000050000 0.00768Copy code

"Look carefully at the execution time of the above two, is there any difference?"

"Wow! The difference between the two results is so big, the global variable access is much slower than the local access! I understand, I understand~~"

"I would like to emphasize to you the shortcomings of using global variables in Lua!"

  • Because it's the overall situation,
    Declaring variable names is easy to conflict
    , The project is maintained by multiple people, it is impossible to avoid it every time
  • The speed of accessing global variables is slower than that of local variables

You have to be more careful when writing code. Think about why it s okay for others to write like this, and you have problems after copying and pasting it? Learn to think inertially, and more importantly, you must find me before submitting the code and going through the testing process

code review

"Okay, boss! I see, I need you more guidance in the future ! I will invite you to drink Starbucks tomorrow afternoon "

"Oh, can I get off work?"

"Go, go, legs are on you, and I didn't hold you away! Go, it's time to get off work, it's already half past eight!"

We walked out of the park together and looked at each other's backs; I seemed to see me who was fledgling at the beginning of the year, but I could not withstand the blows and the pressure from the superiors; looked up at the starry sky and told myself: "Although we have gone through the hardest torment. A part of the journey , but it does not mean that we can relax; we will be beaten if we fall behind, the unchanging truth !"

When we are at a loss: " Work hard, maybe your last straw! ".