简体   繁体   中英

There is no global variables in elixir. How to take variable from one function and use it in another?

I have a boardgame I have to make using elixir. The first function is called readFrom(aString) which will take a string and then extract the variables from it. I don't want to bore you with the 20 variables within the readFrom function that I wrote, so I'll just make it simple for the sake of the question.

defmodule SnakesAndLadders do

def readFrom(aString) do
x=aString
end

def print() do
IO.inspect x
end 
end

So I just need to know a workaround to get variable x and use it into the function print(). Is there any possible way to do this? Thanks.

Given the example code you posted:

defmodule SnakesAndLadders do

   def readFrom(aString) do
      x=aString
      print(x)
   end

   def print(s) do
      IO.inspect s
   end 
end

This would be the simplest way to accomplish this. Don't rely on global variables--pass values to functions.

And given your comment, you'd probably want to do something like this in the readFrom function:

def readFrom("board " <> row column <> rest = aString) do
   {row,column}
end

That assumes that aString starts with "board " . But the concept of decomposing a string via pattern matching is a lot to get into so I'll leave that up to you to research further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM