Lua 值得学习吗？
Lua
![](/data/attachment/album/202211/12/111937y0kior1oyf44tttt.jpg)



> 
> Lua 是一个有趣而强大的语言，随着各个版本的推进，功能愈发的强大，开发者群体也在不断的增长。这篇文章我们将探索一下它的各种前景。
> 
> 
> 


Lua 是一个脚本语言，它面向过程、函数式编程，甚至可以是 [面向对象的](https://opensource.com/article/22/10/object-oriented-lua%20)。它使用类 C 语言的语法，但却是动态类型，具有自动内存管理和垃圾回收功能，使用基于寄存器的虚拟机来解释字节码。这些特点使得它对于初学者来说是个很好的语言，同时也是经验丰富的程序员的强大工具。


虽然与 [Python](https://opensource.com/resources/python) 和 [JavaScript](https://opensource.com/article/22/9/javascript-glossary) 相比，Lua 现在已经有点儿黯然失色了，但是 Lua 拥有的一些优点使得它在许多的重大软件项目中很受欢迎。Lua 很容易嵌入到其他语言当中， 这意味着你可以在（例如）Java 编写的代码中包含 Lua 文件，就像原生的 Java 代码一样运行。这听起来就像魔法一般，现在有许多项目如 [luaj](https://github.com/luaj/luaj) 使得其成为可能，之所以可以实现，正是因为 Lua 就是为此而设计的。部分出于这种灵活性，你可以在许多游戏、图形应用的程序中发现 Lua 脚本的身影。


就像其他任何事情一样，做到完美是需要时间的，但 Lua 是很易于学习（并且有趣）的语言。它是一种一致的语言、一种带有有用的错误消息的友好的语言，并且可以在网上轻松找到许多有用的资料。那么就让我们开始吧！


### 安装 Lua


在 Linux 下，你可以使用发行版自带的包管理来安装 Lua。例如，在 Fedora、CentOS、 Mageia、OpenMandriva 以及类似发行版中：



```
$ sudo dnf install lua

```

在 Debian 以及基于 Debian 的系统中：



```
$ sudo apt install lua

```

对于 Mac，你可以使用 [MacPorts](https://opensource.com/article/20/11/macports) 或者 [Homebrew](https://opensource.com/article/20/6/homebrew-linux)：



```
$ sudo port install lua

```

对于 Windows，可以使用 [Chocolatey](https://opensource.com/article/20/3/chocolatey) 安装 Lua。


完成安装后，可以在终端中输入 `lua` 来在交互式解释器中使用 Lua。


### 函数


如许多编程语言一样，Lua 的语法通常是一个内建的函数或关键字，后面跟着参数。例如，`print` 函数显示你传给它的所有参数。



```
$ lua
Lua 5.4.2  Copyright (C) 1994-2020 Lua.org，PUC-Rio

> print('hello')
hello

```

Lua 的 `string` 库可以操作单词（在编程中称为“字符串”）。例如，要统计字符串中的字母数量，你可以使用 `string` 库中 `len` 函数：



```
> string.len('hello')
5

```

### 变量


变量允许你在计算机内存中为临时的数据创建一个指定的空间。Lua 中创建变量的方法是赋予变量一个名字，接着将数据放入其中。



```
> foo = "hello world"
> print(foo)
hello world
> bar = 1+2
> print(bar)
3

```

### 表


在编程中，数组的使用频率仅次于变量。“数组”这个词的字面意思就是一种排列，而这就是程序中数组的意义了。它是数据的一种排列，因为有排列，所有数组具有结构化的优势。本质上，数组通常用于和变量相同的目的，只不过数组会给对其中的数据进行排序。在 Lua 中，数组被称为“表”。（LCTT 译注：使用过其它编程语言的同学可以发现，Lua 的表相当于其它语言中的关联数组、哈希。）


创建表和创建变量类似，区别仅在于它的初始化内容被设置为 `{}`:



```
> mytable = {}

```

当往表中增加数据时，它就如同创建变量一样，区别在于这里的变量之前总是以表名开头，中间使用 `.` 来连接:



```
> mytable.foo = "hello world"
> mytable.bar = 1+2
> print(mytable.foo)
hello world
> print(mytable.bar)
3

```

### 使用 Lua 编写脚本


在终端交互环境中运行 Lua 可以得到良好的反馈，但是将 Lua 作为脚本运行会更为有用。Lua 脚本就是包含 Lua 代码的文本文件，Lua 命令可以解析并执行此文件。


在刚刚开始学习一门编程语言时，一个永恒的问题是你怎么知道该写什么。这篇文章将提供一个不错的开端，截至目前，你仅知道了两三个 Lua 函数。懂得查阅文档是很关键的。Lua 并不是一个复杂的语言，可以通过 [Lua 文档网站](http://www.lua.org/docs.html) 很方便的获取关键字以及函数的用法。


下面是一个练习题。


假设你想编写一个 Lua 脚本来统计句子中的单词数量。与众多的编程挑战一样，有许多方法可以解决这个问题，假设你在 Lua 文档中找到的第一个相关的函数是 `string.gmatch`，此函数可以搜索字符串中的特定字符。单词通常通过空格分隔开来，所以你决定计算空格数并加 1 来作为单词的数量。


下面是实现的代码：



```
function wc(words,delimiter)
  count=1
  for w in string.gmatch(words，delimiter) do
    count = count + 1
  end

  return count
end

```

下面是这个样例代码的解释：


* `function`：这是声明函数开始的关键字。自定义函数的工作方式与内置函数（如 `print` 和 `string.len`）基本相同。
* `words` 和 `delimiter`：这是函数运行所需的参数。正如 `print('hello')` 当中，`hello` 是一个参数。
* `counter`：一个变量，且被初始化为 `1`。
* `for`：在循环中使用 `string.gmatch` 作为迭代器遍历 `words`，并且在其中搜索`delimiter`。
* `count = count + 1`：当搜索到了 `delimiter`，则对 `count` 进行自增 1 的操作。
* `end`：`for` 循环的结束关键字。
* `return count`：这个函数输出（或返回）`count` 变量的内容。
* `end`：函数结束的关键字。


现在你已经创建了一个函数，你可以使用它。需要记住，函数不会自动运行，而是等待你在代码中调用它。


将下面的代码写入文件并保存为 `words.lua`：



```
function wc(words,delimiter)
  count=1
  for w in string.gmatch(words，delimiter) do
    count = count + 1
  end
  return count
end

result = wc('zombie apocalypse'，' ')
print(result)

result = wc('ice cream sandwich'，' ')
print(result)

result = wc('can you find the bug? '，' ')
print(result)

```

你现在创建了一个 Lua 脚本。你可以使用 Lua 运行它。随后你会发现统计单词的结果有些问题：



```
$ lua ./words.lua
2
3
6

```

你也许已经注意到了最后一个句子的单词统计不正确，因为在句子的最后带有一个额外的空格。Lua正确的检测到了空格，并将其计入 `count` 中，但是单子的统计是错误的，因为有个空格并没有作为单词的分隔出现。我把这个问题留给你来解决，或者去发现其他方法，即使方法不太理想。编程中有很多需要思考的地方。有时是纯粹学术性的思考，有时也许是应用是否运训正常的思考。


### 学习 Lua


Lua 是一个有趣且强大的语言，随着版本的推进，功能愈发的强大，开发者群体也在不断的增长。你可以将 Lua 作为实用性的个人脚本使用，或者在工作中使用，或者仅仅是体验一下一个新的语言。尝试一下，看看 Lua 能给你带来什么吧。


（LCTT 译注：顺便问一句，你知道 “Lua” 怎么发音吗？ ?）




---


via: <https://opensource.com/article/22/11/lua-worth-learning>


作者：[Seth Kenlon](https://opensource.com/users/seth) 选题：[lkxed](https://github.com/lkxed) 译者：[MuggleWei](https://github.com/MuggleWei) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Lua is a scripting language used for procedural programming, functional programming, and even [object-oriented programming](https://opensource.com/article/22/10/object-oriented-lua ). It uses a C-like syntax, but is dynamically typed, features automatic memory management and garbage collection, and runs by interpreting bytecode with a register-based virtual machine. This makes it a great language for beginners, but also a powerful tool for experienced programmers.

Lua has been somewhat eclipsed from the public view by languages like [Python](https://opensource.com/resources/python) and [JavaScript](https://opensource.com/article/22/9/javascript-glossary), but Lua has several advantages that make it popular in some major software projects. Lua is easily embedded within other languages, meaning that you can include Lua files in the code base of something written in (for instance) Java and it runs as if it were native Java code. It sounds like magic, but of course there are projects like [luaj](https://github.com/luaj/luaj) working to make it possible, and it's only possible because Lua is designed for it. It's partly because of this flexibility that you're likely to find Lua as the scripting language for video games, graphic applications, and more.

As with anything, it takes time to *perfect*, but Lua is easy (and fun) to learn. It's a consistent language, a friendly language with useful error messages, and there's lots of great support online. Ready to get started?

## Installing Lua

On Linux, you can install Lua using your distribution's package manager. For instance, on Fedora, CentOS, Mageia, OpenMandriva, and similar distributions:

```
````$ sudo dnf install lua`


On Debian and Debian-based systems:

```
````$ sudo apt install lua`


For Mac, you can use [MacPorts](https://opensource.com/article/20/11/macports) or [Homebrew](https://opensource.com/article/20/6/homebrew-linux).

```
````$ sudo port install lua`


For Windows, install Lua using [Chocolatey](https://opensource.com/article/20/3/chocolatey).

To test Lua in an interactive interpreter, type `lua`

in a terminal.

## Functions

As with many programming languages, Lua syntax generally involves a built-in function or keyword, followed by an argument. For instance, the `print`

function displays any argument you provide to it.

```
``````
$ lua
Lua 5.4.2 Copyright (C) 1994-2020 Lua.org, PUC-Rio
> print('hello')
hello
```


Lua's `string`

library can manipulate words (called "strings" in programming.) For instance, to count the letters in a string, you use the `len`

function of the `string`

library:

```
``````
> string.len('hello')
5
```


## Variables

A variable allows you to create a special place in your computer's memory for temporary data. You can create variables in Lua by inventing a name for your variable, and then putting some data into it.

```
``````
> foo = "hello world"
> print(foo)
hello world
> bar = 1+2
> print(bar)
3
```



## Tables

Second only to the popularity of variables in programming is the popularity of *arrays*. The word "array" literally means an *arrangement*, and that's all a programming array is. It's a specific arrangement of data, and because there is an arrangement, an array has the advantage of being structured. An array is often used to perform essentially the same purpose as a variable, except that an array can enforce an order to its data. In Lua, an array is called a `table`

.

Creating a table is like creating a variable, except that you set its initial content to two braces (`{}`

):

```
````> mytable = {}`


When you add data to a table, it's also a lot like creating a variable, except that your variable name always begins with the name of the table, and is separated with a dot:

```
``````
> mytable.foo = "hello world"
> mytable.bar = 1+2
> print(mytable.foo)
hello world
> print(mytable.bar)
3
```


## Scripting with Lua

Running Lua in the terminal is great for getting instant feedback, but it's more useful to run Lua as a script. A Lua script is just a text file containing Lua code, which the Lua command can interpret and execute.

The eternal question, when just starting to learn a programming language, is how you're supposed to know what to write. This article has provided a good start, but so far you only know two or three Lua functions. The key, of course, is in documentation. The Lua language isn't that complex, and it's very reasonable to refer to the [Lua documentation site](http://www.lua.org/docs.html) for a list of keywords and functions.

Here's a practice problem.

Suppose you want to write a Lua script that counts words in a sentence. As with many programming challenges, there are many ways to go about this, but say the first relevant function you find in the Lua docs is `string.gmatch`

, which can search for a specific character in a string. Words are usually separated by an empty space, so you decide that counting spaces + 1 ought to render a reasonably accurate count of the words they're separating.

Here's the code for that function:

```
``````
function wc(words,delimiter)
count=1
for w in string.gmatch(words, delimiter) do
count = count + 1
end
return count
end
```


These are the components of that sample code:

-
`function`

: A keyword declaring the start of a function. A custom function works basically the same way as built-in functions (like`print`

and`string.len`

.) -
`words`

and`delimiter`

:*Arguments*required for the function to run. In the statement`print('hello')`

, the word`hello`

is an argument. -
`counter`

: A variable set to 1. -
`for`

: A loop using the`string.gmatch`

function as it iterates over the`words`

you've input into the function, and searches for the`delimiter`

you've input. -
`count = count +1`

: For each`delimiter`

found, the value of`count`

is re-set to its*current value*plus 1. -
`end`

: A keyword ending the`for`

loop. -
`return count`

: This function outputs (or*returns*) the contents of the`count`

variable. -
`end`

: A keyword ending the function.

Now that you've created a function all your own, you can use it. That's an important thing to remember about a function. It doesn't run on its own. It waits for you to call it in your code.

Type this sample code into a text file and save it as `words.lua`

:

```
``````
function wc(words,delimiter)
count=1
for w in string.gmatch(words, delimiter) do
count = count + 1
end
return count
end
result = wc('zombie apocalypse', ' ')
print(result)
result = wc('ice cream sandwich', ' ')
print(result)
result = wc('can you find the bug? ', ' ')
print(result)
```


You've just created a Lua script. You can run it with Lua. Can you find the problem with this method of counting words?

```
``````
$ lua ./words.lua
2
3
6
```


You might notice that the count is incorrect for the final phrase because there's a trailing space in the argument. Lua correctly detected the space and tallied it into `count`

, but the word count is incorrect because that particular space happens not to delimit a word. I leave it to you to solve that problem, or to find other ways in which this method isn't ideal. There's a lot of rumination in programming. Sometimes it's purely academic, and other times it's a question of whether an application works at all.

## Learning Lua

Lua is a fun and robust language, with progressive improvements made with each release, and an ever-growing developer base. You can use Lua as a utilitarian language for personal scripts, or to advance your career, or just as an experiment in learning a new language. Give it a try, and see what Lua brings to the table.

## 1 Comment