Sample code for 30+ languages & platforms
Lua

Google Translate Text

See more Google Translate Examples

Demonstrates how to use the Cloud Translation API to translate text from one spoken language to another. The example translates from English to Spanish.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

-- --------------------------------------------------------------------------------
-- IMPORTANT:
-- Don't forget you need to 1st enable the Cloud Translation API in your Google Developers Console at https://console.cloud.google.com
-- --------------------------------------------------------------------------------

-- It is assumed we previously obtained an OAuth2 access token.
-- This example loads the JSON access token file
local jsonToken = chilkat.JsonObject.new()
local success = jsonToken:load_file("qa_data/tokens/_googleTranslate.json")
if not success then
    print("Failed to load _googleTranslate.json")
    return
end

local http = chilkat.Http.new()

http.auth_token = jsonToken:string_of("access_token")

-- The following JSON is sent in the request body.

-- {
--     "q": "The quick brown fox jumped over the lazy dog.",
--     "source": "en",
--     "target": "es",
--     "format": "text"
-- }

local json = chilkat.JsonObject.new()
-- The following code creates the JSON request body.
json:update_string("q", "The quick brown fox jumped over the lazy dog.")
json:update_string("source", "en")
json:update_string("target", "es")
json:update_string("format", "text")

json.emit_compact = false
print(json:emit())

local resp = chilkat.HttpResponse.new()
success = http:http_json("POST", "https://translation.googleapis.com/language/translate/v2", json, "application/json", resp)
if not success then
    print(http.last_error_text)
    return
end

local jResp = chilkat.JsonObject.new()
resp:get_body_json(jResp)
jResp.emit_compact = false

print("Response Body:")
print(jResp:emit())

local respStatusCode = resp.status_code
print("Response Status Code = " .. respStatusCode)
if respStatusCode >= 400 then
    print("Response Header:")
    print(resp.header)
    print("Failed.")
    return
end

-- Sample JSON response:
-- (Sample code for parsing the JSON response is shown below)

-- {
--   "data": {
--     "translations": [
--       {
--         "translatedText": "El zorro r�pida salt� sobre el perro perezoso."
--       }
--     ]
--   }
-- }

local translatedText = ""

local i = 0
local n = jResp:size_of_array("data.translations")
while i < n do
    jResp.i = i
    translatedText = jResp:string_of("data.translations[i].translatedText")
    print(translatedText)
    i = i + 1
end