Merge remote-tracking branch 'LCTT/master'

This commit is contained in:
Xingyu Wang 2021-01-07 18:05:52 +08:00
commit 84cd3e1bed
7 changed files with 406 additions and 170 deletions

View File

@ -1,8 +1,8 @@
[#]: collector: (lujun9972)
[#]: translator: (wxy)
[#]: reviewer: (wxy)
[#]: publisher: ( )
[#]: url: ( )
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-12992-1.html)
[#]: subject: (Learn to use the Sed text editor)
[#]: via: (https://opensource.com/article/20/12/sed)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
@ -12,7 +12,7 @@
> Sed 缺少通常的文本框,而是按照用户的命令直接写入到文件上。
![命令行提示][1]
![](https://img.linux.net.cn/data/attachment/album/202101/07/002353st8vgivu78yzp77v.jpg)
`sed` 命令是为 AT&T 最初的 Unix 操作系统第 7 版创建的,此后,可能每一个 Unix 和 Linux 操作系统都包含了它。`sed` 应用程序是一个 _流编辑器_,与文本编辑器不同的是,它不会打开一个视觉缓冲区,将文件的数据加载到其中进行处理。相反,它根据在终端输入的命令或脚本中的一系列命令,逐行对文件进行操作。

View File

@ -1,27 +1,28 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-12990-1.html)
[#]: subject: (Show progress in your Python apps with tqdm)
[#]: via: (https://opensource.com/article/20/12/tqdm-python)
[#]: author: (Moshe Zadka https://opensource.com/users/moshez)
使用 tqdm 在 Python 应用中显示进度
======
如果你的程序需要一段时间才能显示结果,可通过显示它的进度来避免让用户感到沮丧。
![arrows cycle symbol for failing faster][1]
> 如果你的程序需要一段时间才能显示结果,可通过显示它的进度来避免让用户感到沮丧。
![](https://img.linux.net.cn/data/attachment/album/202101/06/230842thi8skahe68dqa3m.jpg)
阿拉米语,希伯来语和阿拉伯语中的闪米特语根 _q-d-m_ 通常与前进或进度有关。阿拉伯语 _taqaddum_ (تقدّم)的意思是“进度”。进度是很重要的。正如每部感觉良好的电影都会告诉你,旅程和目的地同样重要。
大多数程序都有一个明确的目标,一个期望的最终状态。有时,计算这个最终状态可能需要很长的时间。虽然计算机没有感情不在乎,但人却在乎。人类并不乐意坐在原地等待,而看不到任何明显的进展迹象。疑问不断蔓延。程序崩溃了吗?磁盘是否抖动?操作系统是否把所有的计算资源都分配给了其他任务?
大多数程序都有一个明确的目标,一个期望的最终状态。有时,计算这个最终状态可能需要很长的时间。虽然计算机没有感情不在乎,但人却在乎。人类并不乐意坐在原地等待,而看不到任何明显的进展迹象。疑问不断蔓延。程序崩溃了吗?磁盘性能是否抖动?操作系统是否把所有的计算资源都分配给了其他任务?
就像正义一样,进度必须被看到,而不仅仅是完成。[tqdm][2] Python 库有助于使进度变得明确。
就像正义一样,进度必须被看到,而不仅仅是完成。Python 库 [tqdm][2] 有助于使进度变得明确。
tqdm 模块与控制台一起工作,但它也对我最喜欢的环境之一 Jupyter 有特殊支持。要在 Jupyter 中使用 tqdm你需要导入 `notebook` 子模块并安装 [ipywidgets][3]。`notebook` 子模块与 tqdm 接口兼容。
这意味着你可以做一些导入时操作来导入正确的模块,同时保持 tqdm 的用法不变。诀窍是检查 `__main__` 模块是否有全局变量 `get_ipython`。虽然这只是一个启发式的方法,但却是一个相当准确的方法。
`tqdm` 模块可在控制台下工作,但它也专门支持了我最喜欢的环境之一 Jupyter。要在 Jupyter 中使用 `tqdm`,你需要导入 `notebook` 子模块并安装 [ipywidgets][3]。`notebook` 子模块与 `tqdm` 接口兼容。
这意味着你可以做一些导入时操作来导入正确的模块,同时保持 `tqdm` 的用法不变。诀窍是检查 `__main__` 模块是否具有全局变量 `get_ipython`。虽然这只是一个启发式的方法,但却是一个相当准确的方法:
```
import sys
@ -31,16 +32,14 @@ else:
    import tqdm
```
最简单的情况是,某件事情需要运行一定的迭代次数(事先已知),而每一次迭代的时间都差不多。例如,有一种算法,通过从 1 开始猜测,然后计算一个改进的猜测,来计算任何数字的平方根:
最简单的情况是,某件事情需要运行一定的迭代次数(事先已知),而每一次迭代的时间都差不多。例如,有一个计算任何数字的平方根的算法,通过从 1 作为猜测值开始,然后计算出一个改进后的猜测值:
```
def improve_guess(rt, n):
    return (rt + n/rt) / 2
```
少量改进就能让你很接近。例如,你可以计算 2 的平方根:
一点点的改进可以让你更加接近该平方根。例如,你可以计算 2 的平方根:
```
guess = 1
@ -51,25 +50,25 @@ for i in tqdm.trange(10):
![tqdm output][4]
(Moshe Zadke, [CC BY-SA 4.0][5])
精确到小数点后 10 位!
精确了到小数点后 10 位!
```
`round(2 - guess*guess, 10)`[/code] [code]`0.0`
round(2 - guess*guess, 10)
```
一个稍微复杂一点的例子是,当元素的数量是已知的,而处理每个元素需要类似的时间。例子是,你可以计算一些数字的乘积。为此,你需要一些随机数:
```
0.0
```
一个稍微复杂一点的例子是,当元素的数量是已知的,而处理每个元素需要类似的时间。例如,你可以计算一些数字的乘积。为此,你需要一些随机数:
```
import random
numbers = [random.uniform(0, 2.8) for i in range(100)]
numbers[:5]
```
[/code] [code]
```
[2.6575636572230916,
0.1286674965830302,
1.0634250104041332,
@ -77,27 +76,25 @@ numbers[:5]
0.45192978568125486]
```
现在有了数字,可以将它们相乘了。使用 tqdm 最简单的方法是包装一个 Python 迭代函数。数值是一样的,但是 tqdm 会显示一个进度条:
现在有了这些数字,可以将它们相乘了。使用 `tqdm` 最简单的方法是包装一个 Python 迭代函数。数值是一样的,但是 `tqdm` 会显示一个进度条:
```
result = 1
for num in tqdm.tqdm(numbers):
    result *= num
result
```
[/code] [code]`2.4081854901728303`
```
2.4081854901728303
```
![tqdm output][6]
(Moshe Zadke, [CC BY-SA 4.0][5])
然而,并不是所有的事情都可以预测。最不容易预测的事情之一就是网络速度。当你下载一个大文件时,衡量进度的唯一方法就是检查已经下载了多少:
```
url = "<https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz>"
url = "https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz"
import httpx
with httpx.stream("GET", url) as response:
    total = int(response.headers["Content-Length"])
@ -108,13 +105,10 @@ with httpx.stream("GET", url) as response:
![tqdm output][7]
(Moshe Zadke, [CC BY-SA 4.0][5])
有时,“嵌套”进度条是有意义的。例如,如果你要下载一个目录,你就需要一个进度条来跟踪文件,并为每个文件设置一个进度条。
下面是一个例子(但没有实际下载一个目录):
```
files = [f"vid-{i}.mp4" for i in range(4)]
for fname in tqdm.tqdm(files, desc="files"):
@ -131,8 +125,6 @@ for fname in tqdm.tqdm(files, desc="files"):
![tqdm output][8]
(Moshe Zadke, [CC BY-SA 4.0][5])
所以,如果你的程序需要一段时间才能显示最终结果,为避免让你的用户感到沮丧。请显示它的进度!
--------------------------------------------------------------------------------
@ -142,7 +134,7 @@ via: https://opensource.com/article/20/12/tqdm-python
作者:[Moshe Zadka][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

View File

@ -1,131 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Learn Lua by writing a "guess the number" game)
[#]: via: (https://opensource.com/article/20/12/lua-guess-number-game)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
Learn Lua by writing a "guess the number" game
======
Get to know Lua, a dynamically typed, lightweight, efficient, and
embeddable scripting language, by programming a simple game.
![Puzzle pieces coming together to form a computer screen][1]
If you're a fan of scripting languages like Bash, Python, or Ruby, you might find Lua interesting. Lua is a dynamically typed, lightweight, efficient, and embeddable scripting language with an API to interface with C. It runs by interpreting bytecode with a register-based virtual machine, and it can be used for everything from procedural programming to functional programming to data-driven programming. It can even be used for object-oriented programming through the clever use of arrays, or _tables_, used to mimic classes.
A great way to get a feel for a language is by writing a simple application you're already familiar with. Recently, some Opensource.com correspondents have demonstrated how to use their favorite languages to create a number-guessing game. [Lua][2] is one of my favorites, so here's my Lua version of the guessing game.
### Install Lua
If you're on Linux, you can install Lua from your distribution's software repository. On macOS, you can install Lua from [MacPorts][3] or [Homebrew][4]. On Windows, you can install Lua from [Chocolatey][5].
Once you have Lua installed, open your favorite text editor and get ready to code.
### Lua code
First, you must set up a pseudo-random number generator, so your player has something unpredictable to try to guess. This is a two-step process: first, you start a random seed based on the current time, and then you select a number within the range of 1 to 100:
```
math.randomseed(os.[time][6]())
number = math.random(1,100)
```
Next, create what Lua calls a _table_ to represent your player. A table is like an [array in Bash][7] or an ArrayList in Java. You can create a table and then assign child variables associated with that table. In this code, `player` is the table, and `player.guess` is an entry in that table:
```
player = {}
player.guess = 0
```
For the purpose of debugging, print the secret number. This isn't good for the game, but it's great for testing. Comments in Lua are preceded by double dashes:
```
`print(number) --debug`
```
Next, set up a `while` loop that runs forever upon the condition that the value assigned to `player.guess` is not equal to the random `number` established at the start of the code. Currently, `player.guess` is set to 0, so it is not equal to `number`. Lua's math operator for inequality is `~=`, which is admittedly unique, but you get used to it after a while.
The first thing that happens during this infinite loop is that the game prints a prompt so that the player understands the game.
Next, Lua pauses and waits for the player to enter a guess. Lua reads from files and standard in (stdin) using the `io.read` function. You can assign the results of `io.read` to a variable that is dynamically created in the `player` table. The problem with the player's input is that it is read as a string, even if it's a number. You can convert this input to an integer type using the `tonumber()` function, assigning the result back to the `player.guess` variable that initially contained 0:
```
while ( player.guess ~= number ) do
  print("Guess a number between 1 and 100")
  player.answer = io.read()
  player.guess = tonumber(player.answer)
```
Now that `player.guess` contains a new value, it's compared to the random number in an `if` statement. Lua uses the keywords `if`, `elseif`, and `else` and terminates the statement with the keyword `end:`
```
  if ( player.guess &gt; number ) then
    print("Too high")
  elseif ( player.guess &lt; number) then
    print("Too low")
  else
    print("That's right!")
    os.[exit][8]()
  end
end
```
At the end, the function `os.exit()` closes the application upon success and the keyword `end` is used twice: once to end the `if` statement and again to end the `while` loop.
### Run the application
Run the game in a terminal:
```
$ lua ./guess.lua
96
Guess a number between 1 and 100
1
Too low
Guess a number between 1 and 100
99
Too high
Guess a number between 1 and 100
96
That's right!
```
That's it!
### Intuitive and consistent
As you may be able to tell from this code, Lua is sublimely consistent and fairly intuitive. Its table mechanism is a refreshing way of associating data, and its syntax is minimalistic and efficient. There are few wasted lines in Lua code; in fact, at least one pair of lines in this example could be optimized further, but I wanted to demonstrate data conversion as its own step (maybe you can find the two lines I'm referring to and restructure them).
Lua is a pleasure to use, and its [documentation is a pleasure to read][9], mostly because there's just not that much to it. You'll learn the core language in no time, and then you'll be free to explore [LuaRocks][10] to discover all the great libraries others have contributed to make your time with Lua even easier. "Lua" means "moon" in Portuguese, so give it a try tonight.
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/lua-guess-number-game
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/puzzle_computer_solve_fix_tool.png?itok=U0pH1uwj (Puzzle pieces coming together to form a computer screen)
[2]: https://www.lua.org/
[3]: https://opensource.com/article/20/11/macports
[4]: https://opensource.com/article/20/6/homebrew-mac
[5]: https://opensource.com/article/20/3/chocolatey
[6]: http://www.opengroup.org/onlinepubs/009695399/functions/time.html
[7]: https://opensource.com/article/20/6/associative-arrays-bash
[8]: http://www.opengroup.org/onlinepubs/009695399/functions/exit.html
[9]: https://www.lua.org/docs.html
[10]: https://opensource.com/article/19/11/getting-started-luarocks

View File

@ -1,5 +1,5 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )

View File

@ -0,0 +1,152 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Learn C by writing a simple game)
[#]: via: (https://opensource.com/article/21/1/learn-c)
[#]: author: (Jim Hall https://opensource.com/users/jim-hall)
Learn C by writing a simple game
======
This "guess the number" game is a great introductory program when
learning a new programming language. Here's how to write it in C.
![Business woman on laptop sitting in front of window][1]
I [taught myself about programming][2] back in elementary school. My first programs were on the Apple II, but eventually, I learned C by reading books and practicing. And the best way to practice programming is to write sample programs that help exercise your new knowledge.
One program I like to write in a new language is a simple "guess the number" game. The computer picks a random number from 1 to 100, and you have to figure it out by making guesses. In another article, I showed how to write this ["Guess the number" game in Bash][3], and my fellow Opensource.com authors have written articles about how to write it in [Java][4], [Julia][5], and other computer languages.
What's great about a "Guess the number" game is that it exercises several programming concepts: how to use variables, how to compare values, how to print output, and how to read input.
Over the summer, I recorded [a video series][6] to teach people how to write programs in the [C programming language][7]. Since then, I've heard from many people who are learning C programming by following it. So, I thought I'd follow up by writing a "Guess the number" game in C.
### Pick a random number
Start the "Guess the number" game by writing a function to pick a random number. When writing functions, good programmers try to make them flexible, so they can reuse them to solve slightly different problems. So, instead of hard-coding the function to pick a random number between 1 and 100, write the function to pick a random number between 1 and some integer value `maxval`:
```
#include &lt;stdio.h&gt;
#include &lt;sys/random.h&gt;
int
randnum(int maxval)
{
  /* pick a random number from 1 to maxval */
  int randval;
  getrandom(&amp;randval, sizeof(int), GRND_NONBLOCK);
  /* could be negative, so ensure it's positive */
  if (randval &lt; 0) {
    return (-1 * randval % maxval + 1);
  }
  else {
    return (randval % maxval + 1);
  }
}
```
The function uses the Linux system call `getrandom` to generate a series of random bits. You can learn more about this system call on the man page, but note that `getrandom` will fill the variable with random zeroes and ones. That means the final value could be positive or negative, so you need to do a test afterward to ensure the result of your `randnum` function is a positive value.
### Write the program
You can use this function to write your "Guess the number" program:
```
#include &lt;stdio.h&gt;
#include &lt;sys/random.h&gt;
 
int
randnum(int maxval)
{
  ...
}
int
main(void)
{
  int number;
  int guess;
  number = randnum(100);
  [puts][8]("Guess a number between 1 and 100");
  do {
    [scanf][9]("%d", &amp;guess);
    if (guess &lt; number) {
      [puts][8]("Too low");
    }
    else if (guess &gt; number) {
      [puts][8]("Too high");
    }
  } while (guess != number);
  [puts][8]("That's right!");
  return 0;
}
```
The program starts by picking a random number between 1 and 100 using the `randnum` function. After printing a prompt to the user, the program enters a `do-while` loop so the user can guess the number.
In each iteration of the loop, the program tests the user's guess. If the user's guess is less than the random number, the program prints "Too low," and if the guess is greater than the random number, the program prints "Too high." The loop continues until the user's guess is the same as the random number.
When the loop exits, the program prints "That's right!" and then immediately ends.
```
$ gcc -o guess -Wall guess.c
$ ./guess
Guess a number between 1 and 100
50
Too high
30
Too low
40
Too low
45
Too high
42
Too low
43
Too low
44
That's right!
```
### Try it out
This "guess the number" game is a great introductory program when learning a new programming language because it exercises several common programming concepts in a pretty straightforward way. By implementing this simple game in different programming languages, you can demonstrate some core concepts and compare details in each language.
Do you have a favorite programming language? How would you write the "guess the number" game in it? Follow this article series to see examples of other programming languages that might interest you.
--------------------------------------------------------------------------------
via: https://opensource.com/article/21/1/learn-c
作者:[Jim Hall][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/jim-hall
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/lenovo-thinkpad-laptop-concentration-focus-windows-office.png?itok=-8E2ihcF (Woman using laptop concentrating)
[2]: https://opensource.com/article/20/8/learn-open-source
[3]: https://opensource.com/article/20/12/learn-bash
[4]: https://opensource.com/article/20/12/learn-java
[5]: https://opensource.com/article/20/12/julia
[6]: https://opensource.com/article/20/8/teaching-c
[7]: https://opensource.com/article/20/8/c-programming-cheat-sheet
[8]: http://www.opengroup.org/onlinepubs/009695399/functions/puts.html
[9]: http://www.opengroup.org/onlinepubs/009695399/functions/scanf.html

View File

@ -0,0 +1,94 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (My 3 favorite open source productivity apps)
[#]: via: (https://opensource.com/article/21/1/open-source-productivity-apps)
[#]: author: (Taz Brown https://opensource.com/users/heronthecli)
My 3 favorite open source productivity apps
======
Streamline your agile workflow and increase your productivity.
![Working on a team, busy worklife][1]
Productivity apps can really make your workflow much easier. In this article, I'll share a few of the open source applications I have used to streamline my workflow and increase my overall productivity. All of the productivity applications in this article are free Linux productivity applications.
### Tomboy/Gnote
[Tomboy][2] is a simple note-taking application that can be used on Linux, Windows, and macOS. It's open source under the GNU LGPLv2.
Tomboy is pretty straightforward to use. You write a note, choose whether to make it sticky on your desktop, and delete it when you're done with it.
![Tomboy and Gnote][3]
(Tonya "Taz" Brown, [CC BY-SA 4.0][4])
It (and its clone [Gnote][5]) is a great little application for taking quick notes. Very often, when I am in the middle of doing something, I come up with ideas or thoughts that I want to recall. Tomboy lets me quickly create a note and jot my thoughts down before I forget them. Then I can transfer those ideas to a more permanent place.
### Joplin
[Joplin][6] is an open source note-taking and to-do application. It's cross-platform, available on Linux, Windows, macOS, iOS, and Android, and open source under the MIT License.
![Joplin][7]
(Screenshot of [Joplin repository][8] by Tonya "Taz" Brown, [CC BY-SA 4.0][4])
It can synchronize using cloud syncing services such as Dropbox, OneDrive, Nextcloud, and more. It's easy to install and probably in your Linux repository. It's really two applications in one when you install it on the desktop: You get a standard graphical user interface (GUI) or can open a terminal and use Joplin there.
The desktop has a really nice interface. Notes are organized in notebooks, which essentially makes them your man page. And because the notes are in Markdown format, they show up rendered, and you can edit them in real time. I enjoy using Markdown because it makes it fast for me to write notes. You can also export or import Joplin notes.
### Evolution
[Evolution][9] is an open source personal information management app that's very similar to Outlook, but I think is better for my use. It has email, jobs, notes, links, calendar, and address book functionality. It's open source under the LGPL and other [licenses][10].
![GNOME Evolution][11]
([GNOME][12], [CC BY-SA 4.0][4])
I use it on my desktop computer running Fedora. It is efficient and definitely helps me get through a busy day. It allows me to do business using Linux; what more can I ask?
To use it in Fedora, open a terminal and type the following commands:
```
sudo dnf remove evolution
sudo dnf update
sudo dnf install evolution
sudo dnf install evolution-ews
```
### My go-to tools
These tools are my staples that I have been relying on for some time. Using them beyond their basic capabilities makes me more efficient, effective, and productive. As a technical product manager and agilist, I am proud that I still use Linux and other open source software, even if the companies I work for do not.
* * *
_This article originally appeared on [Course Hero][13] and is republished with permission._
--------------------------------------------------------------------------------
via: https://opensource.com/article/21/1/open-source-productivity-apps
作者:[Taz Brown][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/heronthecli
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/team_dev_email_chat_video_work_wfm_desk_520.png?itok=6YtME4Hj (Working on a team, busy worklife)
[2]: https://wiki.gnome.org/Apps/Tomboy
[3]: https://opensource.com/sites/default/files/uploads/tomboy-gnote.png (Tomboy and Gnote)
[4]: https://creativecommons.org/licenses/by-sa/4.0/
[5]: https://wiki.gnome.org/Apps/Gnote
[6]: https://joplinapp.org/
[7]: https://opensource.com/sites/default/files/uploads/joplin_0.jpg (Joplin)
[8]: https://github.com/laurent22/joplin
[9]: https://wiki.gnome.org/Apps/Evolution
[10]: https://gitlab.gnome.org/GNOME/evolution/-/blob/master/COPYING
[11]: https://opensource.com/sites/default/files/uploads/evolution.png (GNOME Evolution)
[12]: https://help.gnome.org/users/evolution/stable/intro-main-window.html.en
[13]: https://www.coursehero.com/file/74086904/Personal-productivity-using-open-source-software-tools/

View File

@ -0,0 +1,129 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Learn Lua by writing a "guess the number" game)
[#]: via: (https://opensource.com/article/20/12/lua-guess-number-game)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
通过编写“猜数字”游戏学习 Lua
======
通过编写一个简单的游戏来认识 Lua它是一种动态类型的、轻量级的、高效的、可嵌入的脚本语言。
![Puzzle pieces coming together to form a computer screen][1]
如果你是 Bash、Python 或 Ruby 等脚本语言的爱好者,你可能会发现 Lua 很有趣。Lua 是一种动态类型的、轻量级的、高效的、可嵌入的脚本语言,它有与 C 语言的 API 接口。它通过解释字节码与基于寄存器的虚拟机来运行它可以用于从过程式编程到函数式编程再到数据驱动编程。它甚至可以通过巧妙地使用数组或_表_来模拟类以用于面向对象的编程。
感受一门语言的好方法是通过编写一个你已经熟悉的简单应用。最近,一些 Opensource.com 的通讯员已经演示了如何使用他们最喜欢的语言来创建一个数字猜测游戏。[Lua][2] 是我最喜欢的语言之一,所以这是我的 Lua 版猜数游戏。
### 安装 Lua
如果你是在 Linux 上,你可以从你的发行版仓库中安装 Lua。在 macOS 上,你可以从 [MacPorts][3] 或 [Homebrew][4] 安装 Lua。在 Windows 上,你可以从 [Chocolatey][5] 安装 Lua。
安装 Lua 后,打开你最喜欢的文本编辑器,可以准备编写了。
### Lua 代码
首先,你必须设置一个伪随机数生成器,这样你的玩家就有一些不可预知的东西来尝试猜测。这是一个两个步骤的过程:首先,你根据当前的时间生成一个随机种子,然后在 1 到 100 的范围内选择一个数字:
```
math.randomseed(os.[time][6]())
number = math.random(1,100)
```
接下来,创建一个 Lua 所谓的_表_来表示你的玩家。表就像一个 [Bash 中的数组][7]或 Java 中的 ArrayList。你可以创建一个表然后分配与该表相关的子变量。在这段代码中`player` 是表,而 `player.guess` 是表中的一个条目:
```
player = {}
player.guess = 0
```
为了调试打印秘密数字。这对游戏不好但对测试很有帮助。Lua 中的注释前面有双破折号:
```
`print(number) --debug`
```
接下来,设置一个 `while` 循环,当分配给 `player.guess` 的值不等于代码开始时建立的随机 `number` 时,循环将永远运行。目前,`player.guess` 被设置为 0所以它不等于 `number`。Lua 的不等式数学运算符是 `~=`,诚然这很独特,但过一段时间你就会习惯。
在这个无限循环的过程中,首先游戏会打印一个提示,让玩家明白游戏的内容。
接下来Lua 会暂停等待玩家输入猜测。Lua 使用 `io.read` 函数从文件和标准输入 stdin 中读取数据。你可以将 `io.read`的结果分配到一个变量中,这个变量是在 `player` 表中动态创建的。玩家输入的问题是,即使它是一个数字,它也是作为一个字符串读取的。你可以使用 `tonumber()` 函数将这个输入转换为整数类型,将结果赋值回初始为 0 的 `player.guess` 变量:
```
while ( player.guess ~= number ) do
  print("Guess a number between 1 and 100")
  player.answer = io.read()
  player.guess = tonumber(player.answer)
```
现在 `player.guess` 包含了一个新的值,它将与 `if` 语句中的随机数进行比较。Lua 使用关键字 `if`、`elseif` 和 `else`,并用关键字 `end` 来结束语句:
```
  if ( player.guess &gt; number ) then
    print("Too high")
  elseif ( player.guess &lt; number) then
    print("Too low")
  else
    print("That's right!")
    os.[exit][8]()
  end
end
```
最后,函数 `os.exit()` 在成功后关闭应用,关键字 `end` 使用了两次:一次是结束 `if` 语句,另一次是结束 `while` 循环。
### 运行应用
在终端上运行游戏:
```
$ lua ./guess.lua
96
Guess a number between 1 and 100
1
Too low
Guess a number between 1 and 100
99
Too high
Guess a number between 1 and 100
96
That's right!
```
就是这样!
### 直观且一致
从这段代码中可以看出Lua 是非常一致且相当直观的。它的表机制是一种令人耳目一新的数据关联方式它的语法也是简约而高效的。Lua 代码中几乎没有浪费的行数,事实上,这个例子中至少有两行可以进一步优化,但我想把数据转换作为它的步骤来演示(也许你可以找到我所指的两行,并对它们进行重组)。
Lua 使用起来很愉快,它的[文档阅读起来很愉快][9],主要是因为它的内容实在是不多。你会在短时间内学会核心语言,然后你就可以自由地探索 [LuaRocks][10],发现别人贡献的所有很棒的库。
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/lua-guess-number-game
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/puzzle_computer_solve_fix_tool.png?itok=U0pH1uwj (Puzzle pieces coming together to form a computer screen)
[2]: https://www.lua.org/
[3]: https://opensource.com/article/20/11/macports
[4]: https://opensource.com/article/20/6/homebrew-mac
[5]: https://opensource.com/article/20/3/chocolatey
[6]: http://www.opengroup.org/onlinepubs/009695399/functions/time.html
[7]: https://opensource.com/article/20/6/associative-arrays-bash
[8]: http://www.opengroup.org/onlinepubs/009695399/functions/exit.html
[9]: https://www.lua.org/docs.html
[10]: https://opensource.com/article/19/11/getting-started-luarocks