Modifying an Erlang Record [duplicate] - erlang

This question already has answers here:
Adding to an existing value in Erlang
(2 answers)
Closed 7 years ago.
I know that a record in Erlang cannot be changed once it has been set. I am attempting to use a record to increase a value.
add_new_num() ->
Number = random:uniform(6),
STR = #adder{value = 7},
New = add(STR, Number).
add(#adder{value =V} = Adder, Value) ->
Adder#adder{value = V + Value}.
When running add_new_num() I will always get 7 + Number. This is not what I want. I want to get it to do the following.
add_new_num() -> 7 + Number = Val
add_new_num() -> Val + Number = Val2
add_new_num() -> Val2 + Number = Val3
...
How can I achieve this?

There are various ways to do this. Think about where you want to store the value: Erlang doesn't have "static variables" like C, so the function itself cannot remember the value.
You could pass the current record as an argument to add_new_num, and get the updated record from its return value. You could keep a process running, and send messages to query it for the current value and to ask it to increase the value. Or you could store the value in an ETS table, or even Mnesia.

Related

How to make a String become one Number in lua script (Mine question IS not that simple)

I wanna know How to convert a number in one String,in lua script,but i know If do this
Var = 10 ,
then the "var" Will be equal to 10
But my question is not simple I mean Literally transform the number into a String but keep having its value
Example
Var = 10
So if I add 10 + 5 is equal to 15
And what i want is :
Var + 5 = 15
So the "var" despite being a String works as a number
(I want to do this because I can't pull my variable to be displayed in a message (Var) along with another message that will be between "Your number is:"
It’s quite simple, just wrap your variable like this:
var x = tonumber(x)
print(type(x))
-- Output : number.
This converts string x representing a number in base b [2..36, default: 10] to a number, or nil if invalid; for base 10, it accepts full format (e.g. "1.5e6").

New values in tables - shared?

Issue
While trying to learn lua I accidentally found out that if
a = {"a"}
b = a
than this produces (no surprise):
a
{"a"} --[[table: 0x046bde18]]
b
{"a"} --[[table: 0x046bde18]]
but then if:
a[2] = "b"
why is a == b still true?
a
{"a", "b"} --[[table: 0x046bde18]]
b -- this is a surprise
{"a", "b"} --[[table: 0x046bde18]]
This seem to work both ways: if a new value is assigned to b then it will be also assigned to a.
On the other hand if I assign a a value (example: a = 1) and b = a then if a value is changed (a = 2) then b retains the original value (still b = 1).
Questions
Why is this behaviour different depending on wheather a is an array/table or a value? Is it due to built-in metatables (__newindex)?
What is the purpose of such behaviour of arrays/tables?
What if I wanted/needed to somehow seperate a and b (or what to do if I wanted to store the values of a before changing b)?
(I read Lua Assignment and Metatables and Metamethods chapters of the Lua Reference Manual but still have no clue why such behaviour occures.)
In your example, a and b are just references to the same table. In Lua, tables are objects, and you created a table and assigned it to a with the first statement, and then you created a second reference to the same table with the second assignment. So, both a[2] = "b" and b[2] = "b" are acting on the same underlying table (table: 0x046bde18).
A table is not a value, it is an object. a = {"a"} constructs a table and assigns a reference to the table to a. b = a assigns the same reference to b. But, x = 10 assigns the value 10 to x. If y = 10 and you could change the underlying value of 10, I suppose that this change would be reflected in both x and y, but I know of no obvious way to do this. In this code:
x = 10
y = 10
y = y + 1
the resulting values will be x = 10, and y = 11. The underlying value of 10 has not changed, but y was reassigned to the value 11.
If you want to work with two copies of the table that can change independently, you would need to write a function that copies the members of a into b = {}. Here is a question that discusses making copies of tables.

Generated integer array based on number in rails

I want to generate 5 buttons with different values based on one integer.
For example I've got 30, I want to create buttons with 10 20 30 40 50
value = 30
int1 = value - 20
int2 = value - 10
int3 = value
int4 = value + 10
int5 = value + 20
buttoncode = ""
%w{int1 int2 int3 int4 int5}.each do |minutes|
buttoncode += 'buttoncode'
end
I can do it in a very bad way, but it could be done a smarter solution I guess.
Is it possible to make something like that?
%w{sum(max-20) sum(max-10) max sum(max+10) sum(max+20)}.each do |minutes|
end
See Ruby: How to iterate over a range, but in set increments?
So in your case it would be:
(min..max).step(10) do |n|
n += 'buttoncode'
end
By the way, this is not really Rails specific, but Ruby specific. Rails is a web framework that handles the interaction between browser and the web server that is built on top of Ruby.
If you feel like you aren't that up to speed with Ruby, try https://learnrubythehardway.org/book/ and do some exercise on HackerRank or ProjectEuler in Ruby.

Is there a table that can be used to access local variables in Lua? [duplicate]

This question already has answers here:
Access local variable by name
(2 answers)
Closed 6 years ago.
Just like how we can do this:
a = 3
print(_G['a']) -- 3
I want to be able to do something like this:
local a = 3
print(_L['a']) -- 3
I basically want to be able to access local variables using their names as strings. Is there a table that can do this, perhaps one that can be passed as a function argument? It would be like the this keyword in ActionScript.
This is possible by way of the debug library - namely the getlocal and setlocal functions. If you can't use this library (or access the C API), then you're out of luck.
You can extend your global environment with a specially crafted _L table, that when accessed performs linear lookups of the current set of locals.
Reading a local variable simply finds a matching variable name, and returns its value. Writing to a local variable requires you to discover its index in the stack frame, and then update the value accordingly. Note that you cannot create new locals.
Here's a simple example that works with Lua 5.1 (but not Lua 5.2+).
local function find_local (key)
local n = 1
local name, sname, sn, value
repeat
name, value = debug.getlocal(3, n)
if name == key then
sname = name
sn = n
end
n = n + 1
until not name
return sname, sn
end
_G._L = setmetatable({}, {
metatable = false,
__newindex = function (self, key, value)
local _, index = find_local(key)
if not index then
error(('local %q does not exist.'):format(key))
end
debug.setlocal(2, index, value)
end,
__index = function (_, key)
return find_local(key)
end
})
In use:
local foo = 'bar'
print(_L['foo']) --> 'bar'
_L['foo'] = 'qux'
print(_L['foo']) --> 'qux'
local function alter_inside (key)
local a, b, c = 5, 6, 7
_L[key] = 11
print(a, b, c)
end
alter_inside('a') --> 11 6 7
alter_inside('b') --> 5 11 7
alter_inside('c') --> 5 6 11
You could write this in a different manner, using plain functions instead of the table combined with read / write operations (__index, __newindex).
See §2.4 – Metatables and Metamethods if the above use of metatables is a brand new topic for you.
In Lua 5.2+, you can use the special _ENV tables to adjust your current chunk's environment, but note that this is not the same as using local variables.
local function clone (t)
local o = {}
for k, v in pairs(t) do o[k] = v end
return o
end
local function alter_inside (key)
local _ENV = clone(_ENV)
a = 5
b = 6
c = 7
_ENV[key] = 11
print(a, b, c)
end
alter_inside('a') --> 11 6 7
alter_inside('b') --> 5 11 7
alter_inside('c') --> 5 6 11
As a final note, also consider that this (ab)use of locals might not be the best approach.
You could simply store your variables in a table, when appropriate, to achieve the same results with far less overhead. This approach is highly recommended.
local function alter_inside (key)
-- `ls` is an arbitrary name, always use smart variable names.
local ls = { a = 5, b = 6, c = 7 }
ls[key] = 11
print(ls.a, ls.b, ls.c)
end
alter_inside('a') --> 11 6 7
alter_inside('b') --> 5 11 7
alter_inside('c') --> 5 6 11
Don't dig yourself into a hole trying to solve unnecessary problems.

Set integer 'variable' using result of NSString [duplicate]

This question already has an answer here:
Swift: Converting a string into a variable name
(1 answer)
Closed 7 years ago.
I'm using a single action to handle 10 UISwitches by sending a tag value to it. I have a number of integers initialised when launched thus;
int switch_1 = 0;
int switch_2 = 0; etc
When a particular switch is switched on, I want to set the integer to the corresponding integer 'variable' with a 1
So, if switch 2 with tag 2 is turned on, it puts a '1' in the corresponding int 'switch_2' as an integer.
I am getting a string with the right name via 'stringWithFormat' by appending the tag value but don't know how to write the 1 to the corresponding integer variable from it.
Any help would be greatly appreciated. Essentially, I want to write an integer to a 'variable' name with the same name as the generated string value.
Thanks
You can use an array where each index represents your switch, so it would be like following:
int swtichArray[10] = {0}; // if you have 10 switches
While in your action where you handling action of multiple buttons, you could do that:
switchArray[tagOfSwitch] = 1; // if tags are staring from 0 onwards 9

Resources