[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Upvalues vs C static variable
- From: Sean Conner <sean@...>
- Date: Fri, 13 Apr 2018 17:28:08 -0400
It was thus said that the Great Albert Chan once stated:
> When to use lua upvalue mechanism instead of simpler C static variable ?
> Example, lua 5.4 work-1 math.random :
> It uses upvalue to store the 128-bits random state.
> Why not use static uint64_t state ?
To prevent unintentional sharing of data.
Example, a random number generator named spc_rng() (my own special random
number generator) that when seeded with value X will produce the sequence A
-> B -> C -> D ... (why? Perhaps testing purposes or repeatability or what
Case 1---the state is stored in a static C variable. Your program
instantiates two separate Lua VMs (say, you are using then in different
threads of the program). As each thread runs, there will be calls
interspaced to spc_rnd() between the two threads:
so thread1 will "see" the sequence "A C D F" and thread2 will "see" the
sequence "B E G".
Case 2---the state is stored as an upvalue. Your program instantiates two
separate Lua VMs. As each thread runs, there will be calls interspaced to
spc_rnd() between the two threads:
Here, thread1 will "see" the sequence "A B C D" and thread2 will "see" the
sequence "A B C". Which case is important depends upon what you are trying
to do, but in general, case 2 is a safer approach to take since it leads to